Pattern 5 of 18 · Foundations

Sliding Window

A window that grows and shrinks over a sequence to track a running condition in linear time.

A window — a contiguous subarray or substring — expands and shrinks as it moves across the input, so you track a running condition instead of recomputing it from scratch for every possible window.

Key concepts

  • Fixed-size window: the window's length stays constant as it slides.
  • Variable-size window: the right pointer expands the window; the left pointer contracts it when a condition is violated.
  • Maintain running state (a sum, a frequency map, a count of "invalid" characters) as the window moves, rather than recalculating it each time.

When to use it

  • The problem asks for the longest/shortest/best contiguous subarray or substring meeting a condition.
  • Brute force would recompute a sum or count for every possible window — a sign that work can be shared between overlapping ranges.

Tips

  • Ask "when does the window become invalid?" first — that defines when the left pointer should move.
  • A hash map of character counts is the usual companion for string/substring window problems.
  • Each pointer only ever moves forward — that's what keeps this O(n) instead of O(n²).

Practice problems (6)

Blind 75 (4):

More from Blind 150 (2):

See the full roadmap →