Sliding window is the specialized same-direction two-pointer pattern for problems about a contiguous subarray or substring. Instead of recomputing each window from scratch (O(n·k)), you slide a range across the data, adding the entering element and removing the leaving one — one O(n) pass. The whole skill is recognizing "contiguous range + optimize/condition" and knowing which of the two window types you need.
When to reach for it (recognition cues)
- The problem says subarray / substring / contiguous and asks for a max/min/longest/shortest or a count.
- A brute force would re-scan every window (O(n·k) or O(n²)).
- You're tracking a running quantity (sum, character counts, distinct count) as the range moves.
The two variants
Fixed-size window
The window length k is constant. Slide it one step at a time, maintaining the running aggregate.
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
best = window_sum
for right in range(k, len(arr)):
window_sum += arr[right] - arr[right - k] # add entering, drop leaving
best = max(best, window_sum)
return best
Variable-size window (expand & contract)
The window grows until it violates a constraint, then shrinks from the left until it's valid again. This is the workhorse for "longest/shortest ... such that ...".
def longest_unique_substring(s):
seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1 # contract past the duplicate
seen[ch] = right
best = max(best, right - left + 1)
return best
The mental template
For variable windows, almost every solution is the same shape:
- Expand
rightby one, updating window state. - While the window is invalid, shrink from
left, updating state. - Record the answer (longest valid window, or count of valid windows).
Get that loop structure in your fingers and most variants are small edits to "update state" and "invalid condition."
Common problems
Maximum Sum Subarray of Size K (fixed), Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Substring with At Most K Distinct, Permutation in String, Fruit Into Baskets.
Common mistakes
- Confusing fixed vs variable — if the size is given, it's fixed; if it depends on a condition, it's variable (expand/contract).
- Forgetting to update state on both edges — add the entering element and remove the leaving one.
- Recomputing the window each step (defeats the purpose — maintain the aggregate incrementally).
- Off-by-one in window length — it's
right - left + 1.
Complexity
Both variants are O(n) time (each element enters and leaves the window at most once) and O(1) or O(k) space for the window state.
Drill the template on the problems above — build a plan with our free study-plan generator, or get live feedback and mock interviews in our DSA course.
More interview patterns: Two Pointers · Binary Search · Dynamic Programming · Graph Algorithms
Written by Amit Singh — Senior SDE at Amazon, Claude Certified Architect, and founder of AlgoEngineer.