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:

  1. Add up the first 7 days. That is your starting window.
  2. Slide the window one day forward: add the new day, subtract the day that fell off.
  3. 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.

pythonalgorithmssliding-window

See Also