Interactive Lab · DSA & Algorithms

Scan an array once, not k times, the sliding-window trick behind a hundred interview questions

Here's a question you will see: given an array, find the largest sum of any k consecutive elements. The obvious answer re-adds all k numbers for every position, that's O(n·k), and it gets slow fast. The sliding-window trick does it in one pass: keep a running sum, and each time the window moves right, just add the element entering and subtract the element leaving. One add, one subtract, O(1) per step, O(n) total, no matter how wide the window. Drag k and scrub the window across to watch the sum update without ever recomputing.

🎬 Watch the 90-second explainer, then slide the window yourself below ↓

▶ The playground, pick a window size, then slide it across the array

Bars are the array values. The shaded box is the current window of k elements; its running sum is on top. The green underline marks the best window found so far. As the window slides, watch the +entering and −leaving caps.

window k size 3
slide pos 0 of 11

🧭 Where this fits

The sliding window is the streaming pattern of production systems: rate limiters (requests in the last minute), moving averages in monitoring dashboards, TCP flow control, and log-anomaly detection all maintain running aggregates in O(1) per event, exactly the enter-once-leave-once trick you just verified.

The code that's actually running, a running sum, updated in O(1)



  

🔮 Predict, then test

Slide k all the way to its largest and watch the two counters. Predict: which one climbs? The brute-force touches are (n−k+1)·kre-summing k elements at every position, so widening the window makes it do more work. The sliding-window touches stay flat at about 2n: every element enters the sum exactly once and leaves exactly once, whatever k is. That flat line is the whole point, when k grows with the array (say k = n/2), brute force becomes O(n²) while sliding stays O(n). Now: can you find a k where the best window sits at the far right edge?

The takeaway

Your new mental model of the sliding window