All lessons

Sliding Window

7 min · Python examples

Track a moving subarray window to answer range questions without restarting from scratch.

Techniques · Sliding Window0/5 cleared

Enemy 1 of 5

This code finds the biggest total of any 3 numbers in a row. It adds the new number and drops the old one each step, instead of re-adding everything. Press Run to see the best total, 9.

Why this works

A fixed-size window of length k slides across an array. Add the new element entering the window and subtract the one leaving. No need to resum the whole slice each time.

You
Invisible Heisenbug
Loading editor…
Target output: 9