Imagine you're organizing a playlist where no song should play more than k times in any continuous segment. Given an integer array nums and an integer k, you need to find the longest contiguous subarray where each element appears at most k times.
The frequency of an element is how many times it occurs in the subarray. A subarray is considered "good" if every element in it has a frequency โค k.
Goal: Return the length of the longest good subarray.
Example: For nums = [1,2,3,1,2,3,1,2] and k = 2, the longest good subarray could be [1,2,3,1,2,3] with length 6, since each element (1, 2, 3) appears exactly 2 times.
Input & Output
Visualization
Time & Space Complexity
Each element is visited at most twice (once by right pointer, once by left)
Hash map stores at most k different elements in the current valid window
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 105
- 1 โค k โค nums.length
- k represents the maximum allowed frequency for any element