Sliding window
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A sliding window is a stretch of a list that grows on the right and shrinks on the left as you walk along, keeping a running answer instead of recalculating. It is the standard tool for the best, longest or limited stretch of recent activity.
Practical use cases
- Web app: Rate limiting an API to 100 calls per minute. An API allows 100 requests per minute per user. The server keeps a window of recent request times, drops those older than 60 seconds from the left, and adds each new one on the right. If the window already holds 100, the request is refused. Each check costs almost nothing.
- Web app: Spending alert on a prepaid card. A prepaid card app wants to flag any spending above 5,000 rupees within any 7-day stretch. A window slides over daily spending, adding the new day and removing the day that left. Alerts fire exactly when the window total crosses the limit.
- System: Network traffic shaping. Routers and protocols limit how much data may be in flight at once using a window that slides forward as acknowledgements arrive. Streaming tools also compute moving averages over the last few seconds this way, adding the newest reading and dropping the oldest, so the live graph updates smoothly without re-adding hundreds of numbers each time.
The story: Kabir's Pocket Money Stretch
Kabir got pocket money for the week and a stern rule from Dad: "Spend at most 6 rupees in any stretch of days, or I will stop the allowance." Kabir had a list of what he spent each day: 3, 1, 2, 1, 1, 4, 2, 1. He wanted to know the longest run of days where his spending stayed inside the rule.
He tried every start day and every end day, adding the numbers again and again. Mira, peeking at his notebook, drew two small arrows with her pencil: a left arrow and a right arrow, with the days between them as a window.
"Move the right arrow to take in a new day. If the total goes over 6, move the left arrow forward until it is back within 6. Whenever the window is legal, check how many days long it is." The window grew, shrank, grew again. The arrows never moved backward, so each day came in once and went out at most once.
That is a sliding window whose size is not fixed. It stretches while things are good and squeezes when they are bad. It only works when taking in more days can only increase the total (all spends are positive), because then shrinking surely helps.
How to spot this problem, and where you need it
You need the best, longest or limited stretch of recent items, or a moving average, and recounting every stretch from scratch makes the feature slow.
Signs you need it
- The problem says longest, shortest or best stretch of consecutive items satisfying a limit, such as total at most K or no repeats.
- The feature is about the last N minutes, last N requests or last N days, changing as time moves on.
- Your code re-sums or recounts a whole slice inside a loop each time the position moves by one.
Where to use it in a project
- API rate limiters, login-attempt throttles and spam protection counting recent actions per user.
- Moving averages and recent-activity charts on dashboards, and longest-unique-substring or budget-limit checks.
The solution
Keep two markers, left and right, and a running total or count for what is inside. Move the right marker forward to take in one more item and update the running value. While the stretch breaks the rule, move the left marker forward and remove that item from the running value. Record the best stretch seen. Each item enters once and leaves once.
Payoff: Before: recounting every minute of requests per call. After: one add and one remove per request, however busy the API.
Explain it like I am 8
Hold a stretchy rubber band over a row of numbers. Pull the right side to include one more number. If the total gets too big, pull in the left side until it is fine again. Remember the longest the band ever was.
How it works, step by step
- Keep two edges,
landr, and the runningsumof what is inside. - Grow: move
rright by one and add that item tosum. - Shrink: while
sumis over the limit, subtracta[l]and movelright. - Now the window is legal. Record its length
r - l + 1if it is the longest so far. - Repeat until
rreaches the end. Each edge only moves forward, so the total work is about 2n steps.
The code in four languages
PHP
<?php
// Longest run of consecutive days whose total spend is <= $limit
// (works because every spend is positive)
function longestWithin(array $spend, int $limit): int {
$l = 0;
$sum = 0;
$best = 0;
for ($r = 0; $r < count($spend); $r++) {
$sum += $spend[$r]; // grow: take in day r
while ($sum > $limit) { // shrink until legal again
$sum -= $spend[$l];
$l++;
}
$best = max($best, $r - $l + 1); // window is legal here
}
return $best;
}
echo longestWithin([3, 1, 2, 1, 1, 4, 2, 1], 6) . PHP_EOL; // 4 (days 1..4)JavaScript
// Longest run of consecutive days whose total spend is <= limit
// (works because every spend is positive)
function longestWithin(spend, limit) {
let l = 0;
let sum = 0;
let best = 0;
for (let r = 0; r < spend.length; r++) {
sum += spend[r]; // grow: take in day r
while (sum > limit) { // shrink until legal again
sum -= spend[l];
l++;
}
best = Math.max(best, r - l + 1); // window is legal here
}
return best;
}
console.log(longestWithin([3, 1, 2, 1, 1, 4, 2, 1], 6)); // 4 (days 1..4)Java
public class Main {
// Longest run of consecutive days whose total spend is <= limit
// (works because every spend is positive)
static int longestWithin(int[] spend, int limit) {
int l = 0;
int sum = 0;
int best = 0;
for (int r = 0; r < spend.length; r++) {
sum += spend[r]; // grow: take in day r
while (sum > limit) { // shrink until legal again
sum -= spend[l];
l++;
}
best = Math.max(best, r - l + 1); // window is legal here
}
return best;
}
public static void main(String[] args) {
System.out.println(longestWithin(new int[]{3, 1, 2, 1, 1, 4, 2, 1}, 6)); // 4 (days 1..4)
}
}Go
package main
import "fmt"
// longestWithin returns the longest run of consecutive days whose total
// spend is <= limit (works because every spend is positive).
func longestWithin(spend []int, limit int) int {
l, sum, best := 0, 0, 0
for r := 0; r < len(spend); r++ {
sum += spend[r] // grow: take in day r
for sum > limit { // shrink until legal again
sum -= spend[l]
l++
}
best = max(best, r-l+1) // window is legal here
}
return best
}
func main() {
fmt.Println(longestWithin([]int{3, 1, 2, 1, 1, 4, 2, 1}, 6)) // 4 (days 1..4)
}Time: O(n) · Extra space: O(1). The inner while loop looks scary, but l only moves right, so across the whole run it does at most n steps in total.
Watch out for
- Using this on lists with negative numbers. Then taking more items can lower the total and shrinking is no longer a safe move.
- Measuring the length before shrinking, instead of after the window is legal again.
- Forgetting that
r - l + 1is the length (the +1 counts both edges).
Quick check
- When does the left edge move?
- When the window total goes over the limit
- After every step
- Never
- Why is the whole algorithm O(n) even with a while loop inside a for loop?
- The inner loop never runs
- Each edge only moves forward, so each item enters and leaves once
- The array is sorted
- Which input breaks this approach?
- A list with zeros
- A very short list
- A list with negative numbers