Sliding Window Interview Questions
Sliding window problems reward a simple idea executed with discipline: you maintain a contiguous segment that carries just enough information to answer the question—longest, shortest, count of valid windows, maximum sum under a constraint. Interviewers care less about whether you have memorized a template and more about whether you can state an invariant ("the left edge only moves forward when the constraint breaks") and prove each element is touched a bounded number of times.
Patterns that show up constantly
- Variable window with a condition: expand until invalid, then shrink until valid again—classic for "smallest subarray with sum ≥ target" style prompts.
- Fixed-size k: compute the first window in O(k), then slide in O(1) amortized per step when the aggregate metric is incremental (sum, count of distinct chars with a frequency map).
- Monotonic deque inside the window: when you need min or max in every window of size k in linear time—less common in phone screens, more common when the interviewer wants depth.
How to talk while you code
Start with brute force in words—"check every subarray"—so the interviewer knows you understand the search space. Then explain what redundant work you are eliminating. If you use a hash map for character counts, say what happens on shrink: which keys decrement, when you stop. If your window is wrong for five minutes, narrate the bug hunt; senior hires debug in public without spiraling.
STAR angles from real engineering
Maybe you throttled bursty events in a stream, scanned log lines for anomaly windows, or bounded memory while parsing a huge file. You do not need a perfect LeetCode isomorphism—describe the constraint (time or space), the moving boundary, and the outcome. Back at the DSA hub, pair this topic with trees next; interviewers often jump from linear arrays to hierarchical data without a coffee break.
Where you have already seen this
Count API calls in a rolling 60-second window (Python — think APIM + App Insights)
# Simplified: bucket timestamps into a deque of (epoch_sec, count)
from collections import deque
import time
class RollingCounter:
def __init__(self, window_sec: int = 60):
self.window = window_sec
self.q = deque() # (t, n) aggregate buckets
def add(self):
now = int(time.time())
if self.q and self.q[-1][0] == now:
t, n = self.q.pop()
self.q.append((t, n + 1))
else:
self.q.append((now, 1))
self._trim(now)
def _trim(self, now):
while self.q and now - self.q[0][0] >= self.window:
self.q.popleft()
def total(self, now=None):
now = now or int(time.time())
self._trim(now)
return sum(n for _, n in self.q)Product asks: "Are we under the Azure API Management quota before Black Friday?" You are not implementing APIM in the interview—you are showing you understand sliding time buckets, stale edge cleanup, and why wall-clock skew across VMs makes you distrust single-node counters without a shared store.
Questions with sample answers
These are interview-ready outlines—sound human by swapping in your own metrics, team names, and war stories. The examples are generic on purpose so you can map them to what you actually shipped.
Primary prompt
Given an array of integers, find the maximum sum of any contiguous subarray of length exactly k.
Approach: compute sum of first k elements, then slide: add
arr[i], subtractarr[i-k]. O(n) time, O(1) space.Example:
[2, 1, 5, 1, 3, 2], k=3 → windows [2,1,5]=8, [1,5,1]=7, [5,1,3]=9, [1,3,2]=6 → max 9. State the invariant: "window always has exactly k elements."Primary prompt
Find the length of the longest substring with at most k distinct characters—state your window invariant first.
Invariant: expand
rightwhile distinct count ≤ k; when it exceeds k, shrinkleftuntil distinct ≤ k again. Track frequencies in a map; distinct count = map size (or separate counter when freq hits 0).Example:
aabacbebebe, k=2 → longest with ≤2 distinct is "cbebebe" length 7. Each index visited at most twice → O(n).Primary prompt
You have a binary array; find the longest contiguous subarray containing at most m zeros (flip at most m zeros to ones).
Same as "longest subarray with at most m zeros": treat 0 as consuming a flip budget. Variable window: count zeros in window; shrink from left while zeros > m.
Example:
[1,0,0,1,0,1,1], m=2 → take[1,0,0,1,0,1,1]with two zeros… adjust; walk through on whiteboard with counts.Primary prompt
Minimum window substring: given strings s and t, find the smallest window in s that contains all characters of t.
Expand
rightuntil all chars of t are satisfied (need map +formedcount vsrequired), then shrinkleftwhile still valid to minimize length. O(|s|) typical with careful tracking.Edge cases: impossible if t has char not in s; multiple same letters in t require frequency match, not just set membership.
Follow-ups interviewers often ask
Expect nested "why?" questions—brief answers here; expand with your production defaults.
Follow-up
What if the input stream is infinite—how does your approach change?
You cannot store the whole stream; use window over a deque/buffer of last k elements or time-bucketed counts (like rate limiting). For distinct-chars problems, evict left as you stream; memory bounded by alphabet or window size.
Follow-up
Can you achieve O(1) extra space for any variant on this page, or is the hash map essential?
For fixed small alphabet (e.g. ASCII letters only) use fixed array of length 128 instead of map—still O(1) space. For arbitrary Unicode keys, map is needed. Monotonic deque min-in-window is O(k) space by definition.
Follow-up
How do you test window logic without missing off-by-one errors at boundaries?
Unit tests: k=1, n=k, all same, all distinct, negatives if allowed, empty string. Manually trace
left, righton tiny input; property: window size never exceeds rule; after algorithm, verify answer by brute force for small random cases.Follow-up
What is the amortized complexity of moving the right vs left pointer in your solution?
Each index entered and exited at most once → O(n) total pointer moves despite inner while loops—classic amortized linear for two-pointer sliding window.
Follow-up
How would you parallelize or shard this if the array does not fit on one machine (conceptual)?
Partition array by ranges with overlap regions of length k-1 to recompute cross-boundary windows; merge partial answers. Or compute local aggregates and reduce—exact pattern depends on whether metric is associative (sum yes, arbitrary distinct-count windows need more care).