Given a non-empty array of non-negative integers nums
, 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 nums
, that has the same degree as nums
.
def findShortestSubArray(nums):
from collections import defaultdict
# To store the frequency of elements
num_freq = defaultdict(int)
# To store the first position of elements
first_position = {}
# To store the last position of elements
last_position = {}
for i, num in enumerate(nums):
num_freq[num] += 1
if num not in first_position:
first_position[num] = i
last_position[num] = i
# Find the degree of the array
degree = max(num_freq.values())
min_length = float('inf')
# For each number, calculate the length of the subarray if that number contributes to the degree
for num, count in num_freq.items():
if count == degree:
length = last_position[num] - first_position[num] + 1
min_length = min(min_length, length)
return min_length
# Example Usage
nums = [1, 2, 2, 3, 1, 4, 2]
print(findShortestSubArray(nums)) # Output: 6
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?