Sliding Window Pattern

Concepts covered: Sliding Window

A window that moves 1 step at a time

A sliding window is a run of k consecutive items that moves along a sequence 1 position per step. A rolling average on a dashboard, an alert on more than 50 errors in any 5 minutes, and the busiest hour of a day all ask the same question of every stretch of a fixed length. Here are 7 minutes of ride requests with k = 3.

WindowMinutesValuesSum
00 to 24, 7, 213
11 to 37, 2, 918
22 to 42, 9, 516
33 to 59, 5, 115
44 to 65, 1, 814

Compare 2 neighbouring rows. Window 1 drops 4 and picks up 9, but it keeps the 7 and 2 from window 0. Each step shares k - 1 items with the step before it. Summing every window from scratch adds those shared items again each time.

Re-summing versus sliding

requests = [4, 7, 2, 9, 5, 1, 8]
k = 3

for start in range(len(requests) - k + 1):
    window_sum = 0
    for i in range(start, start + k):
        window_sum += requests[i]
    print(start, window_sum)

The sliding version keeps 1 running total. Each step adds requests[i] as it enters on the right and subtracts requests[i - k] as it leaves on the left. That is 2 operations per step, whatever the window size. Take a full day of per-minute counts, 1,440 values, with a 60-minute window. Re-summing reads each value roughly 60 times. Sliding reads each value at most twice, as it enters and again as it leaves.

requests = [4, 7, 2, 9, 5, 1, 8]
k = 3

window_sum = 0
for i in range(k):
    window_sum += requests[i]
best = window_sum
best_start = 0

for i in range(k, len(requests)):
    window_sum += requests[i] - requests[i - k]
    if window_sum > best:
        best = window_sum
        best_start = i - k + 1

print("best window starts at minute", best_start)
print("total requests:", best)
best window starts at minute 1
total requests: 18

The first loop builds the opening window once, by adding every item. From i = 3 on, each step is a single line. Adding 9 and subtracting 4 turns 13 into 18, the new best, so best_start records minute 1. The later sums fall from 16 down to 14 and never beat it. The code stores i - k + 1 because i is where a window ends, and a report wants where it starts.

A sliding sum over [5, 2, 8, 1] with k = 2 holds 10 for the window [2, 8]. Which update moves it to the window [8, 1]?

Windows that grow and shrink

Some questions have no fixed width. Finding the longest run of consecutive log messages that fits in a 6 KB packet needs a window whose size is the answer. A variable window keeps 2 indexes. right moves forward 1 item per iteration, and left moves forward only while the window breaks the rule.

sizes_kb = [2, 1, 3, 4, 1, 1, 2, 1, 5]
limit = 6

left = 0
total = 0
best_len = 0
best_left = 0

for right in range(len(sizes_kb)):
    total += sizes_kb[right]
    while total > limit:
        total -= sizes_kb[left]
        left += 1
    if right - left + 1 > best_len:
        best_len = right - left + 1
        best_left = left

print("longest run:", best_len, "messages")
print("starts at message", best_left)
longest run: 4 messages
starts at message 4

At message 3, a 4 KB message pushes the total to 10, so the inner while drops messages 0 through 2 until the total is back to 4. Messages 4 and 5 join message 3 for 6 KB, exactly the limit, so nothing drops. When message 6 pushes the total to 8, message 3 is dropped. After message 7 arrives, the window holds messages 4 to 7, which total 5 KB and make the longest run. Message 8, at 5 KB, forces 3 more drops.

A while inside a for looks like it could multiply the work, so count the moves instead. left only increases and never passes the end of the list. Over the whole run it advances at most 9 times for 9 messages. The inner loop's total work is therefore capped by the length of the list, the same cap as the outer loop.

About this lesson

This section is part of the Loops: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.