Most sliding window problems in interviews use the same loop. Learn it once and reuse it.
def longest_with_k_distinct(s: str, k: int) -> int:
counts: dict[str, int] = {}
left = best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > k:
counts[s[left]] -= 1
if counts[s[left]] == 0:
del counts[s[left]]
left += 1
best = max(best, right - left + 1)
return best
Five problems with the same shape
- Longest substring without repeating characters.
- Longest substring with at most k distinct characters.
- Minimum window substring.
- Fruit into baskets.
- Maximum sum subarray of size k.
Say the invariant out loud before you code: "the window always holds at most k distinct characters".