Sliding Window Technique
Optimize nested loops by converting O(N^2) algorithms to linear O(N) using a sliding window.
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)toO(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).


