We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium sliding window problem, graded against 7 test cases (4 of them hidden).
A moving window over a contiguous run, expanding and contracting to hold an invariant.
Reach for it when you see: "Longest/shortest contiguous subarray or substring satisfying X."
More Sliding Windowproblems →Maintain a window `[left, right]` and a count of each letter inside it. The window is valid when `windowLength - maxFrequency <= k` (every non-majority character can be replaced). Expand `right` each step; if the window becomes invalid, move `left` forward once.
The subtle trick: `maxFrequency` is never decremented when the window shrinks. A stale (too-high) value can only keep the window from growing, never produce a wrong answer - the answer only improves when a genuinely higher frequency is found.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.