Length of Longest Subarray With at Most K Frequency (LeetCode 2958): Solution and Explanation
Find the longest subarray in which no value appears more than k times.
Intuition
Being good is a property that survives shrinking: if no value appears more than k times in a window, the same holds for any window inside it. That is the condition that makes a sliding window correct.
Grow the window one value at a time and keep a count for every value in it.
Adding nums[right] can only break the rule for that one value, since no other count changed. So when its count passes k, move the left edge right until that count is back to k.
After that, the window is the longest good window ending at right, and its length is a candidate for the answer.
Approach: Sliding window with a frequency map
- Create an empty map
freq, and setleft = 0,best = 0. - For each
right, add one tofreq[nums[right]]. - While
freq[nums[right]] > k, subtract one fromfreq[nums[left]]and incrementleft. - Set
best = max(best, right - left + 1). - Return
best.
Step-by-step example
nums = [1,2,3,1,2,3,1,2], k = 2
- Right moves through indices 0 to 5. Each of 1, 2, 3 reaches count 2, never more, so the window 0..5 has length 6 and
best = 6. - Index 6 adds a third 1. Drop index 0 (a 1), and count[1] is back to 2. The window 1..6 has length 6.
- Index 7 adds a third 2. Drop index 1 (a 2), and the window 2..7 has length 6.
- No window ever grows past 6, so the answer is 6.
Code: Python, Java, C++
1class Solution:
2 def maxSubarrayLength(self, nums: List[int], k: int) -> int:
3 freq = {}
4 left = 0
5 best = 0
6 for right in range(len(nums)):
7 freq[nums[right]] = freq.get(nums[right], 0) + 1
8 while freq[nums[right]] > k:
9 freq[nums[left]] -= 1
10 left += 1
11 best = max(best, right - left + 1)
12 return best1class Solution {
2 public int maxSubarrayLength(int[] nums, int k) {
3 Map<Integer, Integer> freq = new HashMap<>();
4 int left = 0, best = 0;
5 for (int right = 0; right < nums.length; right++) {
6 freq.merge(nums[right], 1, Integer::sum);
7 while (freq.get(nums[right]) > k) {
8 freq.merge(nums[left], -1, Integer::sum);
9 left++;
10 }
11 best = Math.max(best, right - left + 1);
12 }
13 return best;
14 }
15}1class Solution {
2public:
3 int maxSubarrayLength(vector<int>& nums, int k) {
4 unordered_map<int, int> freq;
5 int left = 0, best = 0;
6 for (int right = 0; right < (int)nums.size(); right++) {
7 freq[nums[right]]++;
8 while (freq[nums[right]] > k) {
9 freq[nums[left]]--;
10 left++;
11 }
12 best = max(best, right - left + 1);
13 }
14 return best;
15 }
16};Time and space complexity
O(n)
Both pointers only move right, so each index is added once and removed at most once.
O(n)
The map can hold one entry for every distinct value in the window.
Other approaches
Non-shrinking window (time O(n), space O(n))
Instead of a while loop, move left by at most one step per iteration and keep the window size equal to the best seen so far. The final answer is n - left. Same O(n) time, slightly trickier to reason about.
Binary search on the length (time O(n log n), space O(n))
Check whether a good window of length L exists with a fixed-size sliding window, then binary search L. Works because goodness is monotonic in length, but costs an extra log factor.
Brute force (time O(n^2), space O(n))
Start at every index and extend until some count passes k. Simple but O(n^2).
Common mistakes
- Checking every count after each step. Only the value that just entered can exceed k, so checking that one is enough.
- Using
ifinstead ofwhileto shrink. Several values may have to leave before the offending one does. - Recording the length before shrinking, which counts a window that breaks the rule.
- Values go up to 10^9, so use a hash map rather than an array indexed by value.
Frequently asked questions
Why is it enough to check only nums[right]?
Before adding nums[right], the window was good, so every count was at most k. Adding one value changes only that value's count, so it is the only one that can be over k.
Why does shrinking never skip a better answer?
Any window that starts before the new left and ends at right would contain more than k copies of nums[right], so it is not good. Windows ending later are still considered when right moves on.
What happens when k is at least n?
No count can pass k, the window never shrinks, and the answer is n.