Dynamic and fixed-size windows over contiguous subarrays or substrings
147 problems·16 Easy·93 Medium·38 Hard
Pattern Study Guide & Cheat Sheet· O(n) amortized (each item added and removed at most once) · O(k) or O(min(n, alphabet_size))
▼
Track a contiguous subsegment of an array or string by expanding a right boundary and lazily contracting a left boundary whenever a constraint is broken.
Core Invariant: Monotonicity invariant: As `right` expands, window validity only degrades; advancing `left` only restores validity. Left pointer never moves backward, guaranteeing O(N) total pointer steps.
Recognize it (Keywords & Signals)
Contiguous subarray or substring
Longest / shortest substring meeting constraint K (e.g., at most K distinct chars)
Find minimum size subarray with sum >= S (non-negative numbers)
Fixed window of size K (e.g., maximum average of any subarray of size K)
When NOT to use
Array contains negative numbers and constraint is on sum (monotonicity is broken; must use Prefix Sum + Hash Map).
How to solve (Step-by-step)
1.Initialize `left = 0`, state tracking (e.g., frequency map or running sum), and `ans`.
2.Iterate `right` from 0 to len(arr) - 1, incorporating `arr[right]` into window state.
3.While the window constraint is broken: remove `arr[left]` from state and increment `left += 1`.
4.For longest valid window: update `ans = max(ans, right - left + 1)` after the shrink loop.
5.For shortest valid window: update `ans = min(ans, right - left + 1)` inside or right before the shrink loop.
Watch for (Interview Traps)
Shrinking with `if` instead of `while` when multiple elements must be evicted to restore validity
Forgetting to `del counts[key]` when count drops to 0 (leaving a 0 entry distorts len(counts))
Updating the answer at the wrong time (before vs after shrink loop depending on min vs max window)
Dynamic Sliding Window (Flexible / At Most K)
from collections import defaultdict
def sliding_window_at_most_k(s: str, k: int) -> int:
counts = defaultdict(int)
left = 0
max_len = 0
for right in range(len(s)):
# 1. Expand window: include s[right]
counts[s[right]] += 1
# 2. Shrink window: contract from left while invalid
while len(counts) > k: # e.g., at most k distinct characters
counts[s[left]] -= 1
if counts[s[left]] == 0:
del counts[s[left]] # Must remove key to fix len(counts)
left += 1
# 3. Window [left...right] is now guaranteed valid
max_len = max(max_len, right - left + 1)
return max_len
Cost
O(n) amortized (each item added and removed at most once) · O(k) or O(min(n, alphabet_size)) (State map size bounded by distinct character alphabet (usually <= 26 or 128).)
Canonical problems
#3 Longest Substring Without Repeating Characters:Shrink left until repeated char count drops back to 1
#76 Minimum Window Substring:Expand until all target chars covered, shrink left to minimize length
#209 Minimum Size Subarray Sum:Shrink left while sum >= target to find minimal length
#424 Longest Repeating Character Replacement:Window is valid as long as window_len - max_freq <= k
What is the Sliding Window pattern in coding interviews?
Dynamic and fixed-size windows over contiguous subarrays or substrings It is categorized under Fundamentals and features 147 curated interview problems across Easy (16), Medium (93), and Hard (38) difficulties.
Which tech companies frequently test Sliding Window?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.