Sliding window
Intermediate · 9 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 or stream that moves forward, adding a new item at the front and dropping an old one at the back. You keep the running total or counts up to date instead of recounting the whole stretch each time.
Practical use cases
- Web app: API rate limiter. An API allows 100 requests per minute per user. Keeping a window of the timestamps of the last 60 seconds, adding new ones and dropping old ones, tells instantly whether the next request is allowed, without scanning the full request history. The check costs one small step per request, so the API stays quick even for users who send many requests.
- Web app: Live dashboard moving average. A stock or traffic chart shows the average of the last 10 minutes. Updating the sum by adding the newest value and subtracting the oldest avoids re-adding 600 numbers every second. The chart updates smoothly every second, because only one value is added and one is removed each time.
- Web app: Longest streak without a repeat. A username or word-game checker needs the longest run of letters with no letter repeated. A window grows until a repeat shows up and then shrinks from the left, answering in one pass. The checker answers in one pass over the text, however long the input string is.
- System: TCP flow control. Network connections send a window of packets at a time and slide it forward as acknowledgements arrive. Data keeps flowing without waiting for each packet, so downloads feel faster.
The story: The Rangoli That Never Repeats
It was Diwali, and Zoya was drawing a rangoli border in a long line, one coloured dot at a time. Her grandmother had one rule: "No colour twice inside one stretch of the pattern." Zoya wanted to know how long her longest clean stretch was.
She tried every starting dot and walked forward until a colour repeated, then started again from the next dot. Hundreds of dots, and she kept re-reading the same ones. "There must be a smarter way," she sighed.
Aarav pointed out the smell in the problem: "longest stretch", "contiguous", "no repeats". Those words say: use a window. Keep a window of dots with no repeats. Move the right edge forward to take in a new dot. If that dot is already inside, don't restart; just push the left edge past the old copy. The window always stays clean.
That is the sliding window pattern for variable-size windows. Each dot enters once and leaves at most once, so one pass is enough.
How to spot this problem, and where you need it
You need an answer about every consecutive stretch of a list or time period (last N items, last 60 seconds, longest run), and recomputing each stretch from scratch is wasteful.
Signs you need it
- The wording says "subarray", "substring", "consecutive", "last N minutes", or "longest/shortest stretch such that...".
- You have an outer loop for the start and an inner loop for the end, re-adding or re-counting the same items.
- Moving by one position only changes one item at each end.
Where to use it in a project
- Rate limiting and throttling features that count requests in the last minute or hour.
- Moving averages and live metrics on dashboards that show the last few minutes.
- Text or log checks that look for the longest run meeting some rule.
The solution
Keep two markers, a left and a right edge, plus a running total or a small table of counts for what is inside. Move the right edge to take in a new item and update the total. While the window breaks the rule, move the left edge and remove items. Record the best window seen. Each item enters once and leaves once.
Payoff: Before: recounting 600 values every second. After: one add and one subtract per update.
Explain it like I am 8
Imagine a snake sliding along a row of coloured stones. Its head eats a new stone. If the head meets a colour the snake already holds, the tail shrinks forward until that colour is gone. The snake never goes backwards.
How it works, step by step
- Clues: "longest / shortest / at most k", "substring", "subarray", "contiguous". Think sliding window.
- Keep a window
[left .. right]and some memory of what is inside (here: last position of each letter). - Move right by one every step to take in a new element.
- If the window breaks the rule, move
leftforward until it is valid again. Never move left backwards. - Record the best size after each step. One pass, since both edges only move forward.
The code in four languages
PHP
<?php
// Longest substring without repeating characters
function longestUnique(string $s): int {
$last = []; // letter => index where we last saw it
$left = 0;
$best = 0;
for ($right = 0; $right < strlen($s); $right++) {
$c = $s[$right];
// Seen inside the current window? Jump left past the old copy.
if (isset($last[$c]) && $last[$c] >= $left) {
$left = $last[$c] + 1;
}
$last[$c] = $right;
$best = max($best, $right - $left + 1);
}
return $best;
}
echo longestUnique("abcabcbb"); // 3JavaScript
// Longest substring without repeating characters
function longestUnique(s) {
const last = new Map(); // letter -> index where we last saw it
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
// Seen inside the current window? Jump left past the old copy.
if (last.has(c) && last.get(c) >= left) {
left = last.get(c) + 1;
}
last.set(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}
console.log(longestUnique("abcabcbb")); // 3Java
import java.util.*;
public class Main {
// Longest substring without repeating characters
static int longestUnique(String s) {
Map<Character, Integer> last = new HashMap<>(); // letter -> index where we last saw it
int left = 0;
int best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// Seen inside the current window? Jump left past the old copy.
if (last.containsKey(c) && last.get(c) >= left) {
left = last.get(c) + 1;
}
last.put(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}
public static void main(String[] args) {
System.out.println(longestUnique("abcabcbb")); // 3
}
}Go
package main
import "fmt"
// longestUnique finds the longest substring without repeating characters.
func longestUnique(s string) int {
last := map[byte]int{} // letter -> index where we last saw it
left, best := 0, 0
for right := 0; right < len(s); right++ {
c := s[right]
// Seen inside the current window? Jump left past the old copy.
if i, ok := last[c]; ok && i >= left {
left = i + 1
}
last[c] = right
best = max(best, right-left+1)
}
return best
}
func main() {
fmt.Println(longestUnique("abcabcbb")) // 3
}Time: O(n) · Extra space: O(k). Both edges only move forward, so about 2n moves; the memory holds one entry per different letter (k).
Watch out for
- Moving
leftbackwards when you see a repeat. If the old copy is before the window, ignore it (the>= leftcheck). - Restarting the window from scratch on every repeat, which turns O(n) into O(n²).
- Forgetting to update the best size after every step, not only when the window shrinks.
Quick check
- Which words in a problem hint at a sliding window?
- "longest subarray with at most k..."
- "shortest path"
- "all permutations"
- A repeated letter is found. What do we do?
- Restart at index 0
- Move the right edge back
- Move the left edge past the earlier copy
- Why is this O(n)?
- The array is sorted
- Each edge moves forward at most n times
- We use a hash map