awelgorithms

The sliding window pattern: how to spot it

Updated

A sliding window keeps a contiguous range and its state (a sum, counts, distinct values) and updates them as the range moves, instead of recomputing every subarray. Fixed windows slide by one; variable windows grow on the right and shrink on the left.

When to reach for it

The usual shape

left = 0
state = empty
best = initial
for right, x in enumerate(items):
    add(state, x)
    while invalid(state):
        remove(state, items[left])
        left += 1
    best = better(best, right - left + 1)
return best

4 LeetCode sliding window problems, easiest first

  1. Maximum Average Subarray I easy

    Seed k cells, then slide. Max average is max sum over a fixed length.

  2. Longest Substring Without Repeating Characters medium

    A repeat makes the window invalid. Shrink left until the character is unique again.

  3. Minimum Size Subarray Sum medium

    Expand until the sum is enough, then shrink for the shortest cover.

  4. Max Consecutive Ones III medium

    Zeros are the budget. Too many zeros: slide left until you are back under k.

Skills these problems use

Each one has a free lesson with worked examples and a drill.

All sliding window lessons

check which skills you have 10 minutes, free, no account.

Other patterns