Sliding window

Keep a contiguous range that grows on the right and shrinks on the left, updating a running result as it moves, to solve substring and subarray problems in O(n).

Description

Many problems ask for the best contiguous range: the longest substring without repeated characters, the smallest subarray whose sum reaches a target, the maximum average over any k consecutive days. Checking every range is O(n²) or worse.

A sliding window keeps one range, between a left and a right index, and a running summary of it: a sum, a count of characters, the positions last seen. The right edge moves forward one step at a time. Whenever the window breaks the rule, the left edge moves forward until it's valid again. Each index enters and leaves the window at most once, so the whole scan is O(n).

There are two flavors. A fixed-size window ("any 7 consecutive days") moves both edges together. A variable-size window grows and shrinks according to a condition, as in the example below. The same idea appears in production systems: rate limiters count requests in a sliding time window, and TCP uses a sliding window for flow control.

How it works

a0b1c2a3b4c5b6b7LR

A window from L to R over the characters of a string

  1. index 0: a
  2. index 1: b
  3. index 2: c
  4. index 3: a
  5. index 4: b
  6. index 5: c
  7. index 6: b
  8. index 7: b
A window from L to R over the characters of a string

Step through: the longest substring without a repeated character

a0b1c2a3b4c5b6b7

Step 1 of 15Find the longest run of "abcabcbb" with no repeated character.

0 comparisons

Complexity

OperationAverageWorst
Variable-size windowEach index enters and leaves the window once.O(n)O(n)
Fixed-size window of kO(n)O(n)
Brute force over all rangesO(n²)O(n²) or worse

Space: O(k) for the window's summary (for example, characters seen)

TypeScript implementation

The longest substring without repeats, and a fixed-size window computing the best 3-day sum.

sliding-window.ts
// Two sliding-window problems: a variable-size and a fixed-size window.

/** Longest substring without repeated characters, in one pass. */
export function longestUnique(s: string): string {
  const lastSeen = new Map<string, number>();
  let start = 0, bestStart = 0, bestLen = 0;
  for (let end = 0; end < s.length; end++) {
    const prev = lastSeen.get(s[end]);
    if (prev !== undefined && prev >= start) start = prev + 1; // shrink past the repeat
    lastSeen.set(s[end], end);
    if (end - start + 1 > bestLen) {
      bestLen = end - start + 1;
      bestStart = start;
    }
  }
  return s.slice(bestStart, bestStart + bestLen);
}

/** Best sum of any k consecutive values: slide by adding one and removing one. */
export function bestWindowSum(values: number[], k: number): { sum: number; start: number } {
  let sum = values.slice(0, k).reduce((a, b) => a + b, 0);
  let best = { sum, start: 0 };
  for (let i = k; i < values.length; i++) {
    sum += values[i] - values[i - k];
    if (sum > best.sum) best = { sum, start: i - k + 1 };
  }
  return best;
}

export function demo(): string[] {
  const signups = [12, 8, 15, 22, 19, 7, 30, 28, 5];
  const best = bestWindowSum(signups, 3);
  return [
    `longest unique in "abcabcbb": "${longestUnique("abcabcbb")}"`,
    `longest unique in "pwwkew": "${longestUnique("pwwkew")}"`,
    `best 3 consecutive days of sign-ups: ${best.sum} (days ${best.start + 1}–${best.start + 3})`,
  ];
}

When to use it

Use it when

  • The problem is about a contiguous subarray or substring.
  • You can update a summary in O(1) when one element enters or leaves.
  • Streaming data: moving averages, rate limiting, recent-activity counts.

Avoid it when

  • The range doesn't have to be contiguous: consider dynamic programming or sorting.
  • Shrinking the window doesn't restore validity, for example with negative numbers in minimum-sum problems. Use prefix sums or a deque instead.

Pitfalls

  • Moving the left edge backwards when a repeat was seen before the window started. Check that the last occurrence is inside the window.
  • Recomputing the summary from scratch on every step, which brings back O(n²).
  • Off-by-one window lengths: a window from L to R holds R − L + 1 elements.

Alternatives

Two pointers

Choose it when you're looking for pairs rather than ranges.

Dynamic programming

Choose it when the best range depends on choices that can't be made greedily, such as non-contiguous subsequences.

Monotonic deque

Choose it when you need the maximum or minimum inside each window.