Length of Longest Subarray With at Most K Frequency - Problem

You are given an integer array nums and an integer k.

The frequency of an element x is the number of times it occurs in an array.

An array is called good if the frequency of each element in this array is less than or equal to k.

Return the length of the longest good subarray of nums.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,1,2,3], k = 2
Output: 6
💡 Note: The whole array is good since each element appears at most 2 times: 1 appears 2 times, 2 appears 2 times, 3 appears 2 times.
Example 2 — Frequency Constraint
$ Input: nums = [1,2,1,2,1,2,1], k = 2
Output: 4
💡 Note: Longest good subarray could be [1,2,1,2] with length 4. Element 1 appears 2 times and element 2 appears 2 times.
Example 3 — Single Element
$ Input: nums = [5,5,5,5,5], k = 4
Output: 4
💡 Note: Element 5 can appear at most 4 times, so longest good subarray has length 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Longest Subarray With at Most K Frequency INPUT nums array: 1 i=0 2 i=1 3 i=2 1 i=3 2 i=4 3 i=5 k = 2 max frequency Each element can appear at most k times in a "good" subarray nums = [1,2,3,1,2,3] k = 2 ALGORITHM STEPS 1 Initialize Hash Map Track frequency of elements 2 Sliding Window Use left and right pointers 3 Expand Right Add element, update freq 4 Shrink if freq > k Move left, decrease freq Hash Map State (final): Key Freq 1 2 2 2 3 2 All frequencies <= k=2 FINAL RESULT Longest Good Subarray: 1 2 3 1 2 3 Output: 6 Entire array is "good"! Frequency Check: 1 appears 2 times [OK] 2 appears 2 times [OK] 3 appears 2 times [OK] Key Insight: Use a hash map to track element frequencies in the current window. When any frequency exceeds k, shrink the window from the left until all frequencies are <= k. The sliding window approach ensures O(n) time complexity since each element is visited at most twice (once by right, once by left pointer). TutorialsPoint - Length of Longest Subarray With at Most K Frequency | Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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