Skip to main content

Command Palette

Search for a command to run...

Sliding Window Technique

Optimize nested loops by converting O(N^2) algorithms to linear O(N) using a sliding window.

Updated
โ€ข1 min readโ€ขView as Markdown

The sliding window technique avoids redundant calculations by keeping track of a subset of elements (the "window") as it moves across an array or string.

๐Ÿ“Š How it works

Window of size K = 3:
โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”
โ”‚ 2 โ”‚ 1 โ”‚ 5 โ”‚ 1 โ”‚ 3 โ”‚ 2 โ”‚ 9 โ”‚   -> Sum = 8
โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜

Slide right: Subtract left (2), Add new right (1)
โ”Œโ”€โ”€โ”€โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”
โ”‚ 2 โ”‚ 1 โ”‚ 5 โ”‚ 1 โ”‚ 3 โ”‚ 2 โ”‚ 9 โ”‚   -> Sum = 7
โ””โ”€โ”€โ”€โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜
  • Define the Window: Maintain a start and end boundary.
  • Slide: Shift the window to the right by adding the next element and removing the leftmost element.
  • Time Complexity: Reduces time complexity from O(N * K) to O(N).

When to use? Ideal for problems involving contiguous subarrays or substrings (e.g., finding the maximum sum of K consecutive elements, or longest substring with unique characters).