Arrays and strings · Intermediate
Sliding window
Keep a contiguous range and a running summary of it; extend the right edge, shrink the left edge, and never recompute the range from scratch.
On this page
The idea
Many questions are about contiguous subarrays or substrings: the best one of length k, the longest one with no repeats, the shortest one whose sum reaches a target. Recomputing each candidate costs O(k) or more. A window keeps a summary (a sum, a count map, a set) that is updated in O(1) when one element enters on the right or leaves on the left.
A fixed window moves both edges together. A variable window grows on the right until it becomes invalid (or valid, depending on the goal) and then shrinks on the left until the condition flips again. Because each edge only moves forward, the total work is linear even though there is a loop inside a loop.
How to recognise it
- The answer is a contiguous subarray or substring (words like "consecutive", "stretch", "substring", "window of k").
- The validity of a range changes monotonically: adding elements can only break it (or only fix it), and removing elements does the opposite.
- A brute force enumerates all O(n²) ranges and recomputes a sum or count for each.
When not to use it
- Elements can be negative and the goal is a sum condition: shrinking no longer moves the sum in one direction. Use prefix sums with a hash map instead.
- The range does not need to be contiguous (subsequences): that is usually dynamic programming.
- Validity is not monotonic in the window size, so neither "grow until invalid" nor "shrink until valid" is safe.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# Variable window: longest range that stays valid
state = empty summary # sum, counts, set ...
best = 0
left = 0
for right in range(len(a)):
add(state, a[right])
while not valid(state):
remove(state, a[left])
left += 1
best = max(best, right - left + 1)
return best
# Fixed window of size k
s = sum(a[0:k]); best = s
for right in range(k, len(a)):
s += a[right] - a[right - k]
best = max(best, s)- For "shortest valid range", flip the loop: grow until valid, then shrink while still valid and record the length inside the inner loop.
- The amortized argument: left and right each move at most n times in total, so the inner while costs O(n) over the whole run, not per iteration.
Complexity
Time O(n), extra space O(1) to O(alphabet). Each element enters and leaves the window at most once. Space is whatever the summary needs: a number for sums, a map bounded by the number of distinct symbols for counts.
Worked examples
Longest run without a repeated letter in "abcab"
The window grows to "abc" (length 3). Adding the second "a" makes it invalid, so the left edge drops "a": window "bca". Adding the second "b" drops "b": window "cab". The best length stays 3, found in one pass.
Pitfalls
- Updating the answer before the window is valid again (record after the shrink loop for "longest", inside it for "shortest").
- Forgetting to delete a key whose count reached zero, so "number of distinct keys" stays too high.
- Applying the pattern to sums with negative numbers.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemThe busiest stretch of k hours· beginner · O(n)
- ProblemThe longest stretch without a repeated letter· intermediate · O(n) expected
Learn the foundations
- ModuleM15 Sliding Window· intermediate
- Collectioncollections.deque· Python
- CollectionArrayDeque<E>· Java
- Complexity exerciseA while loop inside a for loop (sliding window)· Θ(n) (amortized O(1) per step)
Related patterns
- PatternTwo pointers· O(n)
- PatternPrefix sums· O(n) build, O(1) per query
- PatternHashing for constant-time lookup· O(n) expected
- PatternMonotonic stack· O(n)
References
dsa.pattern.sliding-window · version 1