Sliding Window

Array Sweeps

Signal

Longest/shortest/max/min contiguous subarray or substring

Template

Grow right, shrink left while the window is invalid.

Worked examples (2)

#1

Sliding Window (fixed size)

Sliding Window (fixed)

Given an integer array and a number k, find the contiguous subarray of length k with the maximum average, and return that average.

function findMaxAverage(nums: number[], k: number): number {
  let windowSum = 0;
  for (let i = 0; i < k; i++) windowSum += nums[i];
  let best = windowSum;
  for (let i = k; i < nums.length; i++) {
    windowSum += nums[i] - nums[i - k]; // add entering, drop leaving
    best = Math.max(best, windowSum);
  }
  return best / k;
}
Insight

Fixed window = O(n) with no inner loop. Recomputing each window would be O(n·k).

#2

Sliding Window (variable size)

Sliding Window (variable)

Given a string, return the length of the longest substring containing no repeated characters.

function lengthOfLongestSubstring(s: string): number {
  const lastSeen = new Map<string, number>();
  let left = 0, best = 0;
  for (let right = 0; right < s.length; right++) {
    const c = s[right];
    const prev = lastSeen.get(c);
    if (prev !== undefined && prev >= left) left = prev + 1; // shrink past the dup
    lastSeen.set(c, right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}
Insight

The window only ever moves right, so each index is visited O(1) times → O(n) overall.