The most direct approach is to examine every possible subarray and check if it satisfies the frequency constraint. For each starting position, we extend the subarray one element at a time, tracking element frequencies as we go. The moment any element appears more than k times, we stop extending and move to the next starting position.
res to track the maximum valid subarray length.i, create a frequency map and iterate through all ending indices j.k, break out of the inner loop.res with the current subarray length j - i + 1.res after checking all subarrays.Instead of restarting from scratch for each position, we can maintain a sliding window that always represents a valid subarray. When adding an element causes a frequency violation, we shrink the window from the left until the constraint is satisfied again. This way, we only process each element twice at most: once when entering and once when leaving the window.
l (left) and r (right) to define the current window.k, shrink the window by incrementing l and decrementing the corresponding frequency.res with the current window size r - l + 1.We can optimize further by observing that we only care about finding the maximum window size. Once we find a valid window of size w, we never need a smaller one. So instead of shrinking the window completely when invalid, we just slide it: move both left and right pointers by one. The window size either stays the same or grows, never shrinks. This guarantees we find the maximum valid window.
cnt, the count of elements whose frequency exceeds k.cnt if it just exceeded k.cnt > 0 (window is invalid), slide the window by moving the left pointer once. Before moving, check if the left element's frequency was above k and decrement cnt accordingly.len(nums) - l.class Solution:
def maxSubarrayLength(self, nums: List[int], k: int) -> int:
count = defaultdict(int)
l = res = 0
cnt = 0 # count of numbers with freq > k
for r in range(len(nums)):
count[nums[r]] += 1
cnt += count[nums[r]] > k
if cnt > 0:
cnt -= count[nums[l]] > k
count[nums[l]] -= 1
l += 1
return len(nums) - lWhen the left pointer moves, you must decrement the frequency count of the element being removed from the window. Failing to do this causes the frequency map to retain stale counts, leading to incorrect constraint checks and wrong answers.
The problem asks for elements appearing "at most k times," meaning frequency should be <= k. Using < k instead of <= k (or > k for violation checks) will incorrectly shrink the window too early or allow invalid windows.
In sliding window problems, update the maximum length after ensuring the window is valid, not before. Updating before shrinking the window can record an invalid window size, resulting in an answer that exceeds the actual longest valid subarray.