Sliding Window Technique — ELI5
Imagine you are sitting on a train, looking out the window. As the train moves, you see different scenery through the same window. You do not need to remember everything you passed — you just pay attention to what is visible right now.
That is the sliding window technique. Instead of looking at every possible group of items in a list (which is exhausting), you look through a “window” that slides along the list. As it slides forward, one new item enters from the right, and one old item drops off the left.
Here is a real example. Say you have a list of daily temperatures for a month, and you want to find the hottest 7-day streak. You could add up every possible group of 7 days — that is a lot of adding. Or you could:
- Add up the first 7 days. That is your starting window.
- Slide the window one day forward: add the new day, subtract the day that fell off.
- Keep track of the biggest total you have seen.
Instead of adding 7 numbers thirty times, you just add and subtract one number each time. Way less work.
The window can be a fixed size (like always 7 days) or it can stretch and shrink. A stretchy window is useful when you want to find the longest streak that meets some rule — like “the longest run of days where temperature stayed above 70°F.” You stretch the window when the rule is met and shrink it when it breaks.
This trick shows up everywhere in programming:
- Finding the longest word without repeating letters
- Finding the smallest group of items that adds up to a target
- Checking if one word is hidden inside another word
One thing to remember: The sliding window technique saves you from checking every possible group by reusing most of your previous work — you only update what changes as the window slides forward.
See Also
- Python Backtracking Algorithms How computers solve puzzles by trying every path, backing up when stuck, and never giving up until they find the answer.
- Python Big O Complexity Analysis Why some programs finish in a blink while others take forever — explained with pizza delivery and toy cleanup.
- Python Binary Search Implementation Find anything in a sorted list insanely fast using the same trick you already use with dictionaries and phone books.
- Python Dynamic Programming The clever trick of remembering answers you already figured out so you never solve the same puzzle twice.
- Python Graph Algorithms How computers navigate maps, friendships, and connections using dots and lines — explained without any math.