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 FrequencyInput: nums = [1,2,3,1,2,3], k = 2123123012345Entire array is valid (each element ≤ k=2 times)Frequency count:• Element 1: appears 2 times ✓• Element 2: appears 2 times ✓• Element 3: appears 2 times ✓Output: 6 (length of longest valid subarray)
Understanding the Visualization
1
Input
Array nums and frequency limit k
2
Process
Find longest subarray with all frequencies ≤ k
3
Output
Length of longest valid subarray
Key Takeaway
🎯 Key Insight: Use sliding window to maintain frequency constraints efficiently in O(n) time
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