Length of Longest Subarray With at Most K Frequency (LeetCode 2958): Solution and Explanation

Medium
Array
Hash Table
Sliding Window

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

  1. Create an empty map freq, and set left = 0, best = 0.
  2. For each right, add one to freq[nums[right]].
  3. While freq[nums[right]] > k, subtract one from freq[nums[left]] and increment left.
  4. Set best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

nums = [1,2,3,1,2,3,1,2], k = 2
  1. 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.
  2. 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.
  3. Index 7 adds a third 2. Drop index 1 (a 2), and the window 2..7 has length 6.
  4. 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 best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Both pointers only move right, so each index is added once and removed at most once.

Space

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 if instead of while to 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.