Array techniquesAnimated
Sliding Window Technique
Slide a fixed or growing window, updating its value incrementally.
Time
O(n)
Extra space
O(1)
Use it for
Best sum of k consecutive items, longest substring problems.
How it works
- We want the largest sum of k consecutive items.
- Compute the sum of the first window.
- To slide right by one, add the new item entering on the right and subtract the item leaving on the left: O(1) per move.
- Track the best sum seen. Total time O(n) instead of O(n·k).
Watch it run
Loading animation…