The Sliding Window Technique: One In, One Out
Emma wants her best three days in a row at the lemonade stand. Instead of adding every group of days again, a sliding window adds the day that comes in and takes away the day that leaves: two steps per slide, however wide the window.
What you will learn
- Explain how a fixed-size window slides by adding the new item and removing the oldest
- Compare re-adding every window, O(n times k), with sliding, O(n), on real step counts
- Trace a sliding window by hand on a small list
- Guard against a window wider than the list
Before you start
- Python lists, loops and indexes
- Big-O notation
Emma has a lemonade stand. This week she sold 4, 2, 7, 1, 8, 6 and 3 cups, one number per day. She wants to know which three days in a row sold the most cups. The plain way is to take every group of three days and add it from scratch: five groups, fifteen additions. The answer is 17 cups, from days five, six and seven. A sliding window gets the same answer without adding every group again.
A frame that slides
Imagine a calendar on the wall and a cardboard frame exactly three days wide. Inside it you see 4, 2 and 7, which add to 13. Slide the frame by one day. Day four comes in on the right, plus 1. Day one falls out on the left, minus 4. You don't need to add all three again: 13 plus 1 minus 4 is 10. Two small steps, and it would still be two steps if the frame were a hundred days wide. One day in, one day out. That's a sliding window.
The plain way: add every window again
def best_window(cups, days):
best = 0
steps = 0
for start in range(len(cups) - days + 1):
sum = 0
for d in range(start, start + days):
sum += cups[d]
steps += 1
best = max(best, sum)
return f"best {best} ({steps:,} steps)"
For every start day, a new sum begins at zero and the inner loop adds all the window's days again. Five windows of three days is fifteen steps, and the same days get added again and again.
The new way: slide the window
def best_window(cups, days):
sum = 0
steps = 0
for d in range(days): # the first window
sum += cups[d]
steps += 1
best = sum
for d in range(days, len(cups)):
sum += cups[d] # the new day comes in
sum -= cups[d - days] # the oldest day leaves
steps += 2
best = max(best, sum)
return f"best {best} ({steps:,} steps)"
Add the first window once. Then slide one day at a time: cups[d] comes in, cups[d - days] leaves, and max keeps the best sum so far. (The lesson names the variable sum, which hides Python's built-in sum() inside the function. That's harmless here, but total is a safer name in your own code.)
import add_again
import sliding_window
# Emma's lemonade stand
cups = [4, 2, 7, 1, 8, 6, 3] # cups sold, day 1 to 7
days = 3 # 3 days in a row
slow = add_again.best_window(cups, days)
fast = sliding_window.best_window(cups, days)
print("Add again: " + slow)
print("Sliding window: " + fast)
Add again: best 17 (15 steps)
Sliding window: best 17 (11 steps)
Step by step
| Step | In | Out | Sum | Best |
|---|---|---|---|---|
| first window (3 steps) | 4, 2, 7 | 13 | 13 | |
| slide 1 | +1 | -4 | 10 | 13 |
| slide 2 | +8 | -2 | 16 | 16 |
| slide 3 | +6 | -7 | 15 | 16 |
| slide 4 | +3 | -1 | 17 | 17 |
Three steps plus four slides of two is eleven. A small win on a week this short, but a big one on a long calendar.
Ten thousand days
import add_again
import sliding_window
cups = [0] * 10_000 # 10,000 days of sales
for d in range(len(cups)):
cups[d] = d % 50
for days in (10, 100, 1_000):
slow = add_again.best_window(cups, days)
fast = sliding_window.best_window(cups, days)
print(f"{days:5,d} days add again: {slow}")
print(f"{days:5,d} days sliding window: {fast}")
10 days add again: best 445 (99,910 steps)
10 days sliding window: best 445 (19,990 steps)
100 days add again: best 2450 (990,100 steps)
100 days sliding window: best 2450 (19,900 steps)
1,000 days add again: best 24500 (9,001,000 steps)
1,000 days sliding window: best 24500 (19,000 steps)
With a 1,000-day window, adding again takes about nine million steps; sliding takes under twenty thousand. And sliding stays about the same whatever the window size, because each day comes in once and leaves once. A wider window hurts the plain way a lot, and the sliding way barely notices.
Breaking it: a window too wide
import sliding_window
cups = [4, 2, 7, 1, 8, 6, 3] # only 7 days
days = 8 # a window of 8 days
print("Window: " + str(days) + " days")
print(sliding_window.best_window(cups, days))
The end of the output:
Window: 8 days
Traceback (most recent call last):
...
sum += cups[d]
~~~~^^^
IndexError: list index out of range
The first window adds days one to seven, then reaches for day eight, cups[7], and there's nothing there. Stopping is the right outcome, since eight days in a row can't fit in a week of seven. A careful program checks first: if days is bigger than len(cups), say so before sliding anything.
What it costs
n is the number of days and k the width of the window.
| Approach | Work per window | Total |
|---|---|---|
| Add every window again | k additions | O(n × k) |
| Sliding window | 2 steps, one in, one out | O(n) |
| First window | k additions, once | one-time cost |
Where you meet it
- A fitness app's best week of steps: the best seven days in a row.
- A video site counting views in the last hour: new views come in, old ones drop out.
- A moving average, like the average of the last seven days.
- A server limit of a hundred requests in the last minute.
Like two pointers, it keeps two positions in a list, but here both move the same way, one window-width apart.
Try it yourself
Change days to 2 and check the best two days in a row by hand before you run it.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
