← Coach Blogs
Coding Interview

Sliding window in Python: one template, five interview problems

One loop and one invariant cover the sliding window problems you meet in coding interviews.

Cem Test · Senior Backend Engineer (test coach)
· 1 min read

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

  1. Longest substring without repeating characters.
  2. Longest substring with at most k distinct characters.
  3. Minimum window substring.
  4. Fruit into baskets.
  5. Maximum sum subarray of size k.

Say the invariant out loud before you code: "the window always holds at most k distinct characters".