Skip to content

Instantly share code, notes, and snippets.

@dmig
Created March 16, 2021 21:08
Show Gist options
  • Save dmig/6356a12d08c113f065919cc175526dea to your computer and use it in GitHub Desktop.
Save dmig/6356a12d08c113f065919cc175526dea to your computer and use it in GitHub Desktop.
"Degree of an Array" test task
'''
Given a non-empty array N, of non-negative integers , the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of N, that has the same degree as N. For example, in the array [1 2 2 3 1], integer 2 occurs maximum of twice. Hence the degree is 2.
Input
Test case input contains 2 lines.
First line contains an integer T, representing the number of elements in the array.
The second line contains the array N, list of T integers each separated by space.
Output
Print the length of the smallest contiguous subarray of input array N, that has the same degree as N.
'''
import fileinput
from collections import Counter
inputData = ''
for line in fileinput.input():
inputData += line
def codeHere():
# Use the function to return the solution.
_, arr = inputData.split('\n')
arr: list = arr.split()
cnt = Counter(arr)
most_common = cnt.most_common()
arr_degree = most_common[0][1]
minl = len(arr)
for el, degree in most_common:
if degree < arr_degree:
break
s = arr.index(el)
e = s
try:
while True:
e = arr.index(el, e + 1)
except ValueError:
pass
minl = min(minl, e - s + 1)
return minl
print(codeHere())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment