Sliding Window
How a sliding window answers questions about runs of neighbouring items in one pass, the fixed and variable-size versions, and what interviewers ask.
On this page
A sliding window is a range of neighbouring items in an array or string, together with a summary of what is inside it, such as a sum, a count or a set of values. When the window moves one step, you update the summary by adding the item that entered and removing the item that left, instead of recomputing it from every item in the range. It is used for questions about the best, longest or shortest run of consecutive items, and it turns an O(n · k) or O(n²) search into a single O(n) pass.
Without it, you would look at every possible run and add it up from scratch. Two neighbouring runs share almost all of their items, so most of that work is repeated.
How a window moves
Keep two indexes, left and right, for the first and last item inside the window. Moving right forward lets one item in, and moving left forward pushes one item out. After each move you adjust the summary for that one item only. If the window holds the items 4, 2, 7 with a sum of 13, then sliding one step to the right gives 13 − 4 + 1 = 10 for the items 2, 7, 1, because only the 4 left and only the 1 entered.
There are two versions of the technique. In the fixed-size version, the window always holds exactly k items. In the variable-size version, the size changes, and the two indexes move independently according to a rule that the window must obey.
Fixed-size window
Use this version when the problem gives you the window size k, for example "the best total over any 3 days in a row". Add up the first k items once. After that, each step adds the new item on the right and subtracts the item that is k places behind it. The trace below finds the best 3-day total in a week of step counts.
sum = steps[0] + ... + steps[k - 1]best = sumfor right from k to n - 1: sum += steps[right] - steps[right - k] best = max(best, sum)- steps04122731485365
- k
- 3
- sum
- 13
- best
- 13
1The first three days add up to 4 + 2 + 7 = 13, so 13 is the best total so far.
- steps04122731right485365
- k
- 3
- sum
- 10
- best
- 13
2The 1 enters and the 4 leaves, so the sum becomes 13 + 1 − 4 = 10.
- steps0412273148right5365
- k
- 3
- sum
- 16
- best
- 16
3The 8 enters and the 2 leaves, so the sum becomes 16, which is a new best.
- steps041227314853right65
- k
- 3
- sum
- 12
- best
- 16
4The 3 enters and the 7 leaves, so the sum becomes 12.
- steps04122731485365right
- k
- 3
- sum
- 16
- best
- 16
5The 5 enters and the 1 leaves, so the sum is 16 again. It ties the best, so
beststays 16. - steps04122731485365
- best
- 16
- windows checked
- 5
6The best 3-day total is 16, first reached on the days holding 7, 1 and 8.
// Largest sum of k neighbouring items. Assumes 1 <= k <= nums.length.
function bestWindowSum(nums, k) {
let sum = 0;
for (let i = 0; i < k; i++) sum += nums[i];
let best = sum;
for (let right = k; right < nums.length; right++) {
sum += nums[right] - nums[right - k]; // one in, one out
best = Math.max(best, sum);
}
return best;
}
bestWindowSum([4, 2, 7, 1, 8, 3, 5], 3); // 16# Largest sum of k neighbouring items. Assumes 1 <= k <= len(nums).
def best_window_sum(nums, k):
total = sum(nums[:k])
best = total
for right in range(k, len(nums)):
total += nums[right] - nums[right - k] # one in, one out
best = max(best, total)
return best
best_window_sum([4, 2, 7, 1, 8, 3, 5], 3) # 16Variable-size window
When the size is not given, the problem asks for the longest or shortest run that satisfies a rule. The right edge moves forward once per item. Whenever the window breaks the rule, the left edge moves forward, removing items, until the rule holds again. This is the same-direction pattern from Two Pointers, with a summary of the window kept alongside the two indexes.
Longest window that satisfies a rule
For each new item at right, first move left forward until adding the item would no longer break the rule. Then add the item and record the window length if it is the best so far. The next example finds the longest run of letters in "streets" with no repeated letter. The summary is a set of the letters in the window, so the question "is this letter already inside?" takes O(1).
for right from 0 to n - 1: while s[right] is in window: remove s[left] from window; left += 1 add s[right] to window best = max(best, right - left + 1)- s0sleft right1t2r3e4e5t6s
- window
- {s}
- best
- 1
1The first
senters the window, which now has length 1. - s0sleft1tright2r3e4e5t6s
- window
- {s, t}
- best
- 2
2The
tenters, and the length is 2. - s0sleft1t2rright3e4e5t6s
- window
- {s, t, r}
- best
- 3
3The
renters, and the length is 3. - s0sleft1t2r3eright4e5t6s
- window
- {s, t, r, e}
- best
- 4
4The first
eenters, and the window "stre" has length 4. - s0s1tleft2r3e4eright5t6s
- window
- {t, r, e}
- best
- 4
5The second
eis already in the window, soleftmoves forward until the oldeis gone. The first removal is thes. - s0s1t2rleft3e4eright5t6s
- window
- {r, e}
- best
- 4
6The window still contains an
e, so thetis removed as well. - s0s1t2r3eleft4eright5t6s
- window
- {e}
- best
- 4
7The window still contains an
e, so theris removed as well. - s0s1t2r3e4eleft right5t6s
- window
- {}
- best
- 4
8Removing the old
eleaves the window empty, so the newecan be added. - s0s1t2r3e4eleft right5t6s
- window
- {e}
- best
- 4
9The new
eenters. The window has length 1, andbeststays 4. - s0s1t2r3e4eleft5tright6s
- window
- {e, t}
- best
- 4
10The
tenters. The earliertalready left the window, so there is no clash, and the length is 2. - s0s1t2r3e4eleft5t6sright
- window
- {e, t, s}
- best
- 4
11The last
senters, and the window "ets" has length 3. - s0s1t2r3e4e5t6s
- best
- 4
- pointer moves
- 11
12The longest run without a repeat is "stre", with length 4.
function longestNoRepeat(s) {
const inWindow = new Set();
let left = 0;
let best = 0;
for (let right = 0; right < s.length; right++) {
while (inWindow.has(s[right])) { // shrink until the rule holds
inWindow.delete(s[left]);
left++;
}
inWindow.add(s[right]);
best = Math.max(best, right - left + 1);
}
return best;
}
longestNoRepeat("streets"); // 4def longest_no_repeat(s):
in_window = set()
left = 0
best = 0
for right in range(len(s)):
while s[right] in in_window: # shrink until the rule holds
in_window.remove(s[left])
left += 1
in_window.add(s[right])
best = max(best, right - left + 1)
return best
longest_no_repeat("streets") # 4Shortest window that reaches a goal
For "the shortest run whose sum is at least a target", the roles are reversed. The right edge grows the window until the goal is reached. At that point you record the length, and then you shrink from the left for as long as the goal still holds, recording a shorter length each time. For the array [2, 3, 1, 2, 4, 3] and the target 7, the answer is 2, from the run 4, 3. This version requires every number to be positive, for the reason given in the section on when a sliding window does not apply.
// Length of the shortest run with sum >= target, or 0 if there is none.
// Assumes every number is positive.
function shortestRunAtLeast(nums, target) {
let sum = 0;
let left = 0;
let best = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) { // shrink while the goal still holds
best = Math.min(best, right - left + 1);
sum -= nums[left];
left++;
}
}
return best === Infinity ? 0 : best;
}
shortestRunAtLeast([2, 3, 1, 2, 4, 3], 7); // 2# Length of the shortest run with sum >= target, or 0 if there is none.
# Assumes every number is positive.
def shortest_run_at_least(nums, target):
total = 0
left = 0
best = float("inf")
for right in range(len(nums)):
total += nums[right]
while total >= target: # shrink while the goal still holds
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
shortest_run_at_least([2, 3, 1, 2, 4, 3], 7) # 2Windows that count distinct items
Some rules cannot be checked with a set, for example "the longest run with at most two different letters". Here the summary is a map from each item to the number of times it appears in the window. When an item leaves, you decrease its count, and you delete the entry when the count reaches zero, so that the size of the map is the number of distinct items. The rest of the loop is the same as the longest-window version: grow on the right, shrink on the left while the rule is broken, and record the length.
Counting windows and windows that need a maximum
Some questions ask how many runs satisfy a rule instead of the best one. If every run that ends at right and starts at or after left is valid, as when the rule is "at most k distinct letters", then each step adds right - left + 1 to the count. A question for exactly k distinct letters is usually answered as the count for at most k minus the count for at most k − 1, because "exactly" is not a rule that stays true when the window shrinks.
When the summary must be the maximum or minimum of the window, a running sum is not enough, because the item that leaves might be the maximum. The standard answer is a double-ended queue that keeps only the indexes of items that could still become the maximum, in decreasing order of value. The front of the queue is always the current maximum, and each index enters and leaves the queue once, so the scan stays O(n).
Complexity
| Approach | Time | Space | Why |
|---|---|---|---|
| Recompute every window | O(n · k) | O(1) | Each of the n windows is added up from scratch with k additions. |
| Fixed window | O(n) | O(1) | Each slide does one addition and one subtraction. |
| Variable-size window | O(n) | O(n) | left and right each move at most n times. The set or map holds at most n items, or at most the alphabet size when the items are letters. |
The while loop inside the for loop looks like O(n²), but left only moves forward and never passes right, so across the whole scan it moves at most n times. Every item enters the window once and leaves at most once.
When a sliding window does not apply
The technique needs the items to be consecutive, because the window is a contiguous range. If the problem asks for a subsequence, where items may be skipped, or for any subset of items, a window cannot represent the answer.
For the variants that shrink the window while a sum is too big or too small, every number must also be non-negative. The loop relies on the sum going down when an item leaves and going up when an item enters. If negative numbers are allowed, removing an item can raise the sum and adding one can lower it, so the loop cannot tell which edge to move, and it throws away windows that would have been the answer. For negative numbers, use prefix sums, usually together with a hash map.
Pitfalls
In the interview
Look for a problem that asks about a contiguous part of an array or string: a subarray or substring that is the longest, the shortest, the largest or the smallest, or one that contains certain characters. Phrases such as "consecutive", "at most k distinct", "no repeated characters", "a sum of at least", or "of length k" point to a window. If the problem allows negative numbers and asks about sums, think of prefix sums first. If the items do not have to be consecutive, a window is the wrong tool.
State the plan before you code: say whether the window is fixed or variable, what the summary holds, when the right edge moves and what makes the left edge move.
Questions to expect:
- "There is a loop inside a loop. Why is this O(n) and not O(n²)?" The inner loop moves
left, andleftnever moves backward and never passesright. Over the whole scan,rightmoves at most n times andleftmoves at most n times, so the total work is at most 2n steps. - "What is the space complexity?" A fixed window with a running sum uses O(1) space. A variable window that keeps a set or a map uses space for the distinct items in the window, which is O(n) in general and O(1) when the alphabet is fixed, for example 26 lowercase letters.
- "Would this still work if the array contained negative numbers?" Not for sum-based windows. The window logic assumes that removing an item lowers the sum, which is false when an item can be negative. You would compute prefix sums and look up earlier prefix values in a hash map, which also runs in O(n).
- "How would you find the longest run with at most k distinct characters?" Keep a map from character to count for the window. Add the new character on the right, and while the map has more than k keys, decrease the count of the character at
left, delete the key if its count reaches zero, and moveleftforward. Record the length after the loop. - "Why a set for no repeated characters, and could you do it faster?" A set gives O(1) membership checks. You can also store the last index of each character in a map and, on a repeat, move
leftdirectly to one past that index, which avoids removing characters one at a time. You must take the larger of the new value and the currentleft, because the earlier occurrence may already be outside the window. The complexity stays O(n), but the left edge makes fewer moves.
The values are [5, 1, 3, 6, 2] and the window size is 3. The first window [5, 1, 3] sums to 9. What is the sum after one slide?
The variable-size version has a while loop inside a for loop. What is its time complexity on a string of length n?
Which task is a poor fit for growing the window on the right and shrinking it on the left while the sum is too big?
In the shortest-run-with-sum-at-least-target code, why is the length recorded inside the while loop?
What to practise next
When you need the sums of many different ranges, in any order, or the numbers can be negative, read Prefix Sums, which answers each range in O(1) after one pass. For the two-index movement that the variable-size window builds on, see Two Pointers.