Meta Data#
Difficulty: medium First Attempt: 2026-01-10
- Submissions: Accepted (first try)
Approach#
The same template as LeetCode 3090, with the limit k instead of 2 and integers instead of characters.
After adding x on the right, only x can exceed k, so shrink the left until it is back to k.
My Solution#
class Solution:
def maxSubarrayLength(self, nums: List[int], k: int) -> int:
cnt = Counter()
left = best = 0
for right, x in enumerate(nums):
cnt[x] += 1
while cnt[x] > k:
cnt[nums[left]] -= 1
left += 1
best = max(best, right - left + 1)
return best
Complexity#
Time O(n), space O(n).
Mistakes to Avoid#
- Writing the shrink condition on the left element: check the newly added
x.
Interview Explanation#
A longest-window slide where each number appears at most k times. After adding x on the right only x can exceed, so I shrink the left until x is back to k and track the longest length. Time O(n).
