Workspace Sliding Window
0d
DSA topics

Sliding Window

A window keeps a contiguous span and updates its summary when either boundary moves.

Picture the idea

A camera frame slides across a row of murals. Only the mural leaving the frame and the one entering it change the view.

When to use it

Use a fixed width or a constraint for which advancing the left boundary predictably restores validity.

How it works

The first width-three sum of [4, 1, 6, 2] is 11. Sliding once subtracts 4 and adds 2, giving 9 without revisiting 1 or 6.

  • Expand the right boundary.
  • Add the entering value or frequency.
  • Shrink from the left until valid.
  • Record the best valid span.

With constant-time summary updates, each boundary passes each item at most once, for O(n) time. Frequency tables need O(k) space for k distinct keys.

Watch for this mistake

The usual minimum-length sum window needs nonnegative values. Negative values break the monotonicity of shrinking.

State whether your interval is inclusive or half-open and derive the length from that convention.

Practice in the lab

Related learning