BeginnerCoder

Lesson 19 — Sliding window

Sliding window: reuse the overlap

Find the biggest sum of k consecutive numbers. Re-adding k numbers at every position is wasteful, because neighbouring windows share k − 1 numbers. Instead, slide: add the new number entering on the right and subtract the one leaving on the left.

# window [1, 4, 2] = 7 -> slide right by one: 7 + 10 - 1 = 16 = [4, 2, 10]

Why it matters: moving averages, "busiest hour" reports and network rate-limiters all slide a window in O(n) instead of O(n × k).

Want it another way?
Task

Write the slide update for s. Expected: 21 (the window 1, 0, 20), then 10.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Algorithms Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.