Many interview questions ask about a contiguous stretch of data: the best week of sales, the longest listening session without a repeated song, the shortest run of orders that reaches a goal. The brute-force answer looks at every stretch separately, recomputing each one from scratch. A sliding window recognizes that two neighboring stretches share almost everything, and only updates what changed at the edges.
Fixed-Size Windows
When the stretch has a fixed length, add the item that enters on the right and subtract the one that leaves on the left:
const visits = [40, 25, 60, 10, 75, 30];
let total = visits[0] + visits[1] + visits[2];
const totals = [total];
for (let right = 3; right < visits.length; right++) {
total += visits[right] - visits[right - 3];
totals.push(total);
}
console.log(totals);
Each total reuses the one before it: