Skip to content

Sliding Window

Sliding Window in under a minute

A window is a contiguous range [left, right] of an array or string. Instead of re-examining every range from scratch (O(n²)), you slide it: extend right by one, and move left forward only when the window breaks a rule. Each index enters and leaves the window at most once, so the total work is O(n).

  • The problem asks about a contiguous subarray or substring.
  • You want the longest, shortest, or best range satisfying a condition.
  • The condition can be checked incrementally (a count, a sum, a set of seen characters).
  • Brute force tries every start and end pair.
  • Keywords: “substring”, “subarray”, “at most k”, “without repeating”, “contains all of”.
left = 0
state = {} # counts, sum, last-seen index: whatever the rule needs
best = 0
for right, item in enumerate(items):
add(state, item) # 1. grow: take in the new element
while window_is_invalid(state): # 2. shrink until the rule holds again
remove(state, items[left])
left += 1
best = max(best, right - left + 1) # 3. record (for "shortest", record inside a valid window)

Longest-valid problems record after shrinking. Shortest-valid problems (like Minimum Window Substring) shrink while the window is still valid and record on each step.