The degree of an array is the highest number of times any single value occurs in it. For [5, 8, 5] the degree is 2, because 5 shows up twice.
Given a non-empty array nums of non-negative integers, return the length of the shortest contiguous subarray whose degree equals the degree of the whole array.
Example 1
Input: nums = [2, 9, 9, 4, 2, 4, 4] Output: 4 Why: degree is 3 (value 4); [4, 2, 4, 4] keeps all three
2 more examples and the constraints
Example 2
Input: nums = [6, 6, 1, 1] Output: 2 Why: 6 and 1 both reach degree 2; [6, 6] is 2 long
Example 3
Input: nums = [7] Output: 1 Why: the whole array is one element
Constraints
- 1 ≤ length of nums ≤ 50,000
- 0 ≤ nums[i] ≤ 49,999
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count, then rescan each tied valueO(n · t)
- One pass with first indexO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 distinct values | Verdict |
|---|---|---|---|
| Count, then rescan each tied value | O(n · t) | Correct, but slow with many ties | |
| One pass with first index | O(n) | Best; one pass, no rescans |
n = length of nums, t = number of values that reach the degree.
Edge cases to test
- One element. [7] has degree 1 and the answer is 1.
- All values different. Every value ties at degree 1, so the answer is 1.
- Several values tie. [6, 6, 1, 1]: both have degree 2; the shortest span wins.
- The degree value is spread out. [3, 1, 1, 3, 2, 3]: 3 occurs three times, from index 0 to 5, so the answer is 6.
- All the same. [4, 4, 4] needs the whole array: 3.
Common mistakes
- Returning the degree itself instead of the length of the subarray.
- Updating best only when the count strictly grows, so a tie with a shorter span is missed.
- Measuring from the value's last index to the end, instead of from its first index to its last.
How to talk through it
- 1Clarify. Is the array non-empty? Is the answer a length, not the subarray itself?
- 2Reframe. The subarray must hold every copy of a most-frequent value, so only first and last positions matter.
- 3Give the two-pass idea. Count, find the degree, rescan each tied value; note it is slow with many ties.
- 4Do it in one pass. Track count and first index together, and update best on a new or tied degree.
- 5Test out loud. Run [7], a tie like [6, 6, 1, 1], and a spread-out value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?