← Lessons

quiz vs the machine

Gold1380

Algorithms

Sliding Window

Maintain a moving range over a sequence to answer subarray questions efficiently.

5 min read · core · beat Gold to climb

Sliding Window

A sliding window maintains a contiguous range over an array or string and slides it forward, updating a running summary instead of recomputing from scratch. It is ideal for questions about the best or shortest subarray meeting a condition.

Fixed window

When the window size is fixed, you add the new element entering on the right and subtract the element leaving on the left as you slide. The running sum or count updates in constant time per step.

Variable window

When the size can grow or shrink, expand the right edge to include more, then contract the left edge whenever the window violates a constraint. This is common for the longest substring without repeats, where you shrink until the duplicate is gone.

Why it is fast

Each element enters the window once and leaves at most once, so the total work is linear even though the window length changes. Compare this to recomputing each subarray from zero, which would be quadratic.

Key idea

A window that grows and shrinks lets each element be processed a constant number of times, keeping the scan linear.

Check yourself

Answer to earn rating on the learn ladder.

1. In a variable sliding window, what do you do when the window violates a constraint?

2. Why is the sliding window linear overall?