Skip to the page

Linear patterns · mid

Sliding window

A sliding window keeps a range [left, right] and updates its state as right grows and left shrinks, so problems about the best contiguous substring or subarray run in O(n) instead of checking every range.

The notes

What you must know

  • Fixed size k: add the new element, remove the one leaving (sum = sum + a[i] - a[i - k]).
  • Variable size: expand right every step; while the window is invalid, shrink left; record the answer when it is valid.
  • State is usually a hash map or a count array plus a counter (for example the number of 'missing' characters in minimum window substring).
  • Longest substring without repeats: store the last index of each character; left = max(left, last[ch] + 1). The max matters ('abba').
  • Sliding window maximum: a deque of indices with decreasing values gives O(n) (Java ArrayDeque, Python collections.deque, C++ std::deque); a heap gives O(n log n).
  • It works for sums only when all numbers are non-negative; with negatives use prefix sums and a hash map.

The red pen

Common traps: mistake → fix

  • Mistake: Recompute the window from scratch each step

    Fix: that is O(n·k); update it step by step.

  • Mistake: left = last[ch] + 1 is enough

    Fix: left must never move backwards: use max.

  • Mistake: Sliding window works for 'sum equals k' with negative numbers

    Fix: it does not; the shrink step cannot be decided.

Easy to hard

Questions interviewers ask, easy to hard

  1. Longest substring without repeating characters.
  2. Maximum sum of any window of size k.
  3. Minimum window substring that contains all characters of t (with repeats).
  4. Maximum of every window of size k in O(n).

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview