Degree of an Array - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,2,3,1]
›
Output:
2
💡 Note:
The degree is 2 (both 1 and 2 appear twice). The shortest subarray with degree 2 is [2,2] with length 2.
Example 2 — Multiple Same Degree
$
Input:
nums = [1,2,2,3,1]
›
Output:
2
💡 Note:
Elements 1 and 2 both have degree 2. Element 1 spans from index 0 to 4 (length 5), element 2 spans from index 1 to 2 (length 2). Shortest is 2.
Example 3 — All Different Elements
$
Input:
nums = [1,2,3,4,5]
›
Output:
1
💡 Note:
All elements appear once, so degree is 1. Any single element subarray has degree 1, so minimum length is 1.
Constraints
- 1 ≤ nums.length ≤ 50,000
- 0 ≤ nums[i] ≤ 49,999
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [1,2,2,3,1] has degree 2 (max frequency)
2
Find Candidates
Elements with max frequency: 1 and 2
3
Calculate Spans
Find shortest span containing all occurrences
Key Takeaway
🎯 Key Insight: The shortest subarray with maximum degree spans from first to last occurrence of the most frequent element with minimum span
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code