Sliding Window
A sliding window is a contiguous range of an array or string that you move from left to right, updating a summary of what is inside instead of recomputing it. It turns problems that look like "check every subarray" (O(n²) or worse) into a single pass, O(n), because each element enters the window once and leaves it once.
This lesson is for software engineering and data candidates preparing for a live coding round. It covers the two kinds of window, the loop template that solves most of these problems, a worked example, and the condition that tells you when the pattern breaks. Code is in Python.
When the pattern fits
The cue is almost always in the wording:
"Contiguous" subarray or "substring", never "subsequence" (a subsequence can skip elements, and windows cannot).
"Longest", "shortest", "maximum sum of length k", "how many" combined with a condition on what is inside.
The condition changes predictably as the window grows. Adding an element only makes the window "more" of something: a bigger sum (when all values are non-negative), more distinct characters, more repeats.
That last point is the one candidates miss. A window works when its condition is monotonic: growing the window can only push it one way (toward too many distinct characters, or toward a sum that meets the target) and shrinking can only push it back. If values can be negative, adding an element might lower the sum, the window loses that property, and you need prefix sums instead (see Hash Maps and Prefix Sums).
Fixed-size windows
When the window length k is given, slide it one step at a time: add the element entering on the right and remove the one leaving on the left.
def max_window_sum(nums, k):
# assumes 1 <= k <= len(nums)
window = sum(nums[:k])
best = window
for right in range(k, len(nums)):
window += nums[right] - nums[right - k]
best = max(best, window)
return bestOn [2, 1, 5, 1, 3, 2] with k = 3 the window sums are 8, 7, 9 and 6, so the answer is 9 (the run 5, 1, 3). Recomputing each sum from scratch would cost O(n·k); the slide costs O(n).
Fixed windows also answer "does any window of length k contain a permutation of this word?" Keep a count of letters in the window, compare it with the word's counts, and update both as the window slides. A neat refinement is to track how many letters currently have matching counts, so each step is O(1) instead of comparing two whole maps.
Variable-size windows: the template
When the length is not given, the window grows and shrinks. One template covers nearly every case:
def variable_window(items):
left = 0
state = ... # counts, a sum, a set: whatever the condition needs
best = ...
for right, item in enumerate(items):
add item to state
while the window is invalid:
remove items[left] from state
left += 1
update best using the window items[left:right + 1]
return bestTwo decisions make it fit a specific problem:
What makes the window invalid? Write it as a condition on
statebefore coding.Where do you record the answer? For "longest valid window", record after the shrink loop, when the window is valid again. For "shortest window that meets a target", flip the loop condition: shrink while the window still meets the target, and record inside the loop before each shrink, because shrinking is what makes it shorter.
The while inside the for looks like O(n²) but is not: left only moves forward, so across the whole run it advances at most n times. Say this when you state the complexity; interviewers often ask.
Worked example: longest stretch with at most k distinct characters
Prompt: "Given a string and an integer k, return the length of the longest substring that contains at most k distinct characters."
Start by restating the problem with an example: for "eceba" and k = 2, the answer is 3 ("ece"). Then name the brute force (check every substring and count its distinct characters, O(n²) with a running count, worse without) and the cue: contiguous, longest, and a condition (distinct count) that only grows as the window grows. That is a variable window.
State: a map from character to its count in the window. Invalid when the map has more than k keys. Record after shrinking.
from collections import defaultdict
def longest_with_k_distinct(s, k):
counts = defaultdict(int)
left = 0
best = 0
for right, ch in enumerate(s):
counts[ch] += 1
while len(counts) > k:
out = s[left]
counts[out] -= 1
if counts[out] == 0:
del counts[out]
left += 1
best = max(best, right - left + 1)
return bestTrace "eceba", k = 2:
e: counts {e: 1}, best 1.c: {e: 1, c: 1}, best 2.e: {e: 2, c: 1}, best 3.b: three keys, invalid. Removee(count 1), still three keys; removec(deleted). Window is"eb", best stays 3.a: three keys again. Removee(deleted). Window"ba", best 3.
Then the edges: k = 0 (the answer is 0, and the loop handles it because every window is invalid), an empty string, and a string with fewer than k distinct characters (the whole string). Deleting a key when its count hits zero is the line most people forget; without it, len(counts) never goes down, the shrink loop pushes left past right, and the code crashes with an index error on this very input.
Time is O(n): each character is added once and removed at most once. Space is O(k) for the map, at most k + 1 keys at any moment.
Compare how two candidates reach this code. The weaker one starts typing a nested loop, gets told it is too slow, writes the window by trial and error, and reruns "eceba" until it prints 3. The stronger one says the brute force and its cost, names the cue and the invalid condition before coding (problem solving), keeps the state in one map with a clear name (code quality), traces the input step by step as above (correctness), raises k = 0 and the empty string without being asked (testing and edge cases), and explains why the nested while is still linear (communication). The final code is the same; the evidence for each scored dimension is not.
The shortest-window variant
"Return the length of the shortest subarray whose sum is at least a target; all values are positive." Same template, answer recorded inside the shrink loop:
def shortest_at_least(nums, target):
left = 0
window = 0
best = float("inf")
for right, x in enumerate(nums):
window += x
while window >= target:
best = min(best, right - left + 1)
window -= nums[left]
left += 1
return 0 if best == float("inf") else bestFor [2, 3, 1, 2, 4, 3] and target 7 this returns 2 (the run 4, 3). Note the agreed return value when no window qualifies; clarify it at the start rather than guessing.
Tip
Before coding, say the invalid condition and where you record the answer in one sentence: "The window is invalid when it has more than k distinct characters; I record the length after shrinking." Most sliding-window bugs are one of those two decisions made inconsistently.
Follow-ups to expect
The AI interviewer lets you drive, then asks for your complexity and for tests. If you are stuck on the brute force, the first hint is a nudge ("what work repeats between neighboring substrings?"); later hints get more specific. Each one is counted, and the dimension it helped with is scored on what you did on your own, so reach for the window before you need the second hint. After a working solution, expect:
"What if the numbers can be negative?" The window property breaks: shrinking no longer reliably lowers the sum. Switch to prefix sums with a hash map, or, for "shortest subarray with sum at least k" with negatives, a monotonic deque. Naming why the window fails scores higher than knowing the fix.
"Return the substring, not the length." Store the best
leftandrightalongside the length."Stream of characters, unbounded input?" The window only needs its state and the elements it still contains, so memory is bounded by the window, not the stream.
"Count the windows instead." For "number of subarrays with at most k distinct", each valid window ending at
rightcontributesright - left + 1subarrays. "Exactly k" is "at most k" minus "at most k - 1".
What changes with seniority
Early-career candidates are expected to reach a correct window with a hint or two. Mid-level candidates should recognize the pattern from the wording, choose fixed or variable without help, and justify the O(n) bound. Senior candidates are expected to handle the variants quickly, especially the "exactly k" trick and the negative-numbers follow-up, and to explain why the window property holds.
Mistakes that cost points
Using a window on a subsequence problem. Windows are contiguous by definition.
Shrinking with
ifinstead ofwhile. One step of shrinking may not restore validity.Not deleting zero-count keys, so the distinct count never drops.
Recording the answer in the wrong place for the longest versus shortest variant.
Assuming non-negative values without saying so. State the assumption, or ask.
Practice it
Drill for 15 minutes: write the template from memory, then adapt it three times without looking: longest substring with no repeated character, fixed window maximum average, and shortest subarray with sum at least a target. For each, say the invalid condition and where you record the answer before you code.
Then practice on Two Sum and be ready to explain why it is not a window problem: the pair need not be adjacent, so there is no contiguous range to slide. Previous in this series: Two Pointers. Next: Binary Search.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Binary Search
Write one boundary-search template without off-by-one bugs, derive exact, first, last and count searches from it, and binary search on the answer and on rotated arrays.
9 min read
- Hash Maps and Prefix Sums
Use maps for lookup, counting and grouping, build prefix sums for constant-time range queries, and count or find target-sum subarrays with a map of earlier prefixes, negatives included.
8 min read
- Stacks and Monotonic Stacks
Solve nested-structure problems with a stack, find the next greater or smaller element for every position in one pass, and explain the push-once, pop-once reason it runs in linear time.
8 min read
- Heaps and Top K
Recognize when a problem needs a heap, code its four shapes (top k, k-way merge, two heaps for a running median, scheduling by earliest end) and say when a plain sort or quickselect is the better answer.
9 min read
