← Sliding Window

Micro-Drill #266 — Frequency window (longest repeating replacement)

Sliding Window Target: 15s

Window is valid when (window_size - max_freq) <= k. max_freq only needs to increase — shrinking the window can't help.

count = {}
l = max_freq = 0
for r in range(len(s)):
    count[s[r]] = count.get(s[r], 0) + 1
    max_freq = max(max_freq, count[s[r]])
    if (r - l + 1) - max_freq &gt; k:
        count[s[l]] -= 1
        l += 1

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #265 Micro #267 →