Builds onTwo pointersHash map lookup
01The idea
A sliding window is a range of items next to each other, from index left to index right. Instead of checking every range, which takes O(n²) or worse, you move the window across the array in one pass:
- Grow the window by moving
rightone step and adding the new item. - If the window breaks a rule, shrink it by moving
leftand removing the item that leaves. - When the window follows the rule again, use it. Record its length, its sum or whatever the problem asks for.
You keep a running summary of what is inside the window, such as a total or a count of each character. Adding and removing one item updates it in O(1), so you never add up the window from scratch.
Both pointers only move forward. Each item enters the window once and leaves at most once. That is why the whole walk is O(n), even though there is a loop inside a loop.
The window works because of one property. If a window breaks the rule, any longer window with the same left end breaks it too. So once the window breaks the rule, left can move forward.
02How to spot it
A sliding window fits when the problem:
- asks about a contiguous subarray or substring, with words such as "longest", "shortest" or "at most"
- has a rule you can check as items come and go: a total under a limit, at most k distinct characters, no repeated characters
- gives a fixed window size k, such as "the largest sum of any k items in a row"
For a fixed size k, you do not need the shrink loop. Add the new item and remove the item that is k steps behind.
Watch out for negative numbers. If items can be negative, adding an item can lower the total, so a window that breaks the rule can fix itself by growing. Then the window logic fails, and prefix sums are the right tool.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue