331. Degree of an Array

Easy
Frequency and Boundary Tracking
Hashing

Problem

The degree of an array is the maximum frequency of any of its elements. Given a non-empty integer array nums, return the smallest possible length of a contiguous subarray that has the same degree as nums.

Examples

Example 1

Input: [1,2,2,3,1]
Output: 2

Example 2

Input: [1,2,2,3,1,4,2]
Output: 6

Example 3

Input: [1]
Output: 1
Constraints

1 <= nums.length <= 50000

0 <= nums[i] <= 50000

Hints

?? For each value, track frequency, first index and last index.

?? Find the overall degree.

?? Among values reaching that degree, minimize lastIndex - firstIndex + 1.

Expected Complexity
Time: O(n)
Space: O(n)
Follow-up

Can you gather all necessary information in a single pass?

Practice Notes

Attempts: 0

Time spent: 0min

Hints used: 0

00:00
Loading...
Case 1
Case 2
Case 3
Input
[1,2,2,3,1]
Expected
2