Skip to content
StackDecode
Array techniquesAnimated

Sliding Window Technique

Slide a fixed or growing window, updating its value incrementally.

Time

O(n)

Extra space

O(1)

Use it for

Best sum of k consecutive items, longest substring problems.

How it works

  1. We want the largest sum of k consecutive items.
  2. Compute the sum of the first window.
  3. To slide right by one, add the new item entering on the right and subtract the item leaving on the left: O(1) per move.
  4. Track the best sum seen. Total time O(n) instead of O(n·k).

Watch it run

Loading animation…