mediumSliding WindowTwo PointersSliding Window

Max Consecutive Ones III

mediumTime: O(n)Space: O(1)

Signals to notice

longest subarray of 1s after flipping at most k zeroscontiguous window with limited flips

Brute force first

Try every subarray, count zeros, check if ≤ k. Each subarray independently counts its zeros. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Sliding window: expand right; when zero count exceeds k, shrink left. The window always contains at most k zeros. Track the maximum window length. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The window represents a subarray where at most k zeros have been 'flipped' to ones. All elements in the window are either 1 or a flipped 0. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Actually flipping the zeros in the array — don't modify the array. Just count zeros in the window and pretend they're flipped. The fix is usually to return to the meaning of each move, not just the steps themselves.

Sliding Window Pattern