Degree of an Array - Problem
Find the Shortest Subarray with Maximum Frequency
Given a non-empty array of non-negative integers
Your mission: find the smallest possible length of a contiguous subarray that has the same degree as the original array. In other words, find the shortest subarray that contains all occurrences of the most frequent element(s).
Example: In
Given a non-empty array of non-negative integers
nums, imagine you're analyzing data patterns where certain values appear more frequently than others. The degree of this array is defined as the maximum frequency of any element within it.Your mission: find the smallest possible length of a contiguous subarray that has the same degree as the original array. In other words, find the shortest subarray that contains all occurrences of the most frequent element(s).
Example: In
[1,2,2,3,1], both 1 and 2 appear twice (degree = 2). The shortest subarray containing all 1's is [1,2,2,3,1] (length 5), but the shortest subarray containing all 2's is [2,2] (length 2). So the answer is 2. Input & Output
example_1.py โ Basic Case
$
Input:
[1, 2, 2, 3, 1]
โบ
Output:
2
๐ก Note:
The array has degree 2 (both 1 and 2 appear twice). The shortest subarray containing all 1's is the entire array (length 5), but the shortest subarray containing all 2's is [2, 2] at indices 1-2 (length 2). Return the minimum: 2.
example_2.py โ Single Element
$
Input:
[1, 2, 2, 3, 1, 4, 2]
โบ
Output:
6
๐ก Note:
The array has degree 3 (element 2 appears 3 times at indices 1, 2, and 6). The shortest subarray containing all occurrences of 2 spans from index 1 to 6: [2, 2, 3, 1, 4, 2] with length 6.
example_3.py โ All Same Elements
$
Input:
[1, 1, 1, 1]
โบ
Output:
4
๐ก Note:
All elements are the same, so the degree is 4. The shortest (and only) subarray with the same degree is the entire array, so the answer is 4.
Constraints
-
nums.lengthwill be between 1 and 50,000 -
nums[i]will be an integer between 0 and 49,999 - The array is non-empty
- All integers are non-negative
Visualization
Tap to expand
Understanding the Visualization
1
Survey the City
Drive through once, counting store locations and noting first/last positions
2
Identify Popular Chains
Find which store chain(s) have the most locations (degree)
3
Calculate Routes
For each popular chain, measure distance from first to last location
4
Choose Shortest
Select the shortest route among all popular chains
Key Takeaway
๐ฏ Key Insight: The shortest subarray with maximum degree spans from the first to last occurrence of any element with maximum frequency - we don't need to check every subarray!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code