Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

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.

Seven days of cups: 4, 2, 7, 1, 8, 6, 3. A three-day frame over days 1 to 3 totals 13. Sliding one day adds day 4 (plus 1) and removes day 1 (minus 4), giving 10. 4 2 7 1 8 6 3 first window: 4 + 2 + 7 = 13 slide: 13 + 1 - 4 = 10 - 4 leaves + 1 comes in best: 8 + 6 + 3 = 17
Each slide is two steps: add the new day, take away the oldest.

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

StepInOutSumBest
first window (3 steps)4, 2, 71313
slide 1+1-41013
slide 2+8-21616
slide 3+6-71516
slide 4+3-11717

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.

ApproachWork per windowTotal
Add every window againk additionsO(n × k)
Sliding window2 steps, one in, one outO(n)
First windowk additions, onceone-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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 19 of 21

Previous
The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
Next post
Greedy Algorithms: The Best-Looking Choice, Right Now

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.

On this page

  • A frame that slides
  • The plain way: add every window again
  • The new way: slide the window
  • Step by step
  • Ten thousand days
  • Breaking it: a window too wide
  • What it costs
  • Where you meet it
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.