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
Degree of an Array INPUT nums = [1, 2, 2, 3, 1] 1 i=0 2 i=1 2 i=2 3 i=3 1 i=4 Frequency Count: 1: 2 2: 2 3: 1 Degree = 2 (max frequency) Position Tracking: 1: first=0, last=4 2: first=1, last=2 3: first=3, last=3 ALGORITHM STEPS 1 Build Hash Maps Track freq, first, last index 2 Find Degree Max frequency = 2 3 Check Elements With freq == degree 4 Calculate Lengths last - first + 1 Subarray Length Calc: For 1: 4-0+1 = 5 For 2: 2-1+1 = 2 Min length = 2 Smallest subarray: [2, 2] at indices 1-2 FINAL RESULT Original Array: 1 2 2 3 1 Subarray [2,2] Output: 2 OK - Verified Shortest subarray with same degree as nums has length 2 Key Insight: Use three hash maps: one for frequency count, one for first occurrence index, and one for last occurrence index. For elements with max frequency (degree), the shortest subarray containing all occurrences is (last_index - first_index + 1). Return the minimum among all such lengths. TutorialsPoint - Degree of an Array | Hash Map Approach
Asked in
Google 15 Facebook 12 Amazon 8
89.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen