🚀 Sliding-Window Technique: A Hands-On Guide
The “sliding window” is a pattern for scanning contiguous segments of an array / string while keeping the work per move constant (or logarithmic with the help of a data structure).
Think of it as having a physical window you slide along a ruler: at any time you can read what’s inside without rereading everything from scratch.
1️⃣ When Do I Reach for Sliding Window?
| Signal you see in a problem | Why SW fits |
|---|
| “Contiguous subarray / substring” | Windows are literally contiguous |
| Need to compute min / max / sum / average / frequency of current window | These can be updated incrementally |
| Constraints are “big” (𝑁 up to 10⁵+) | O(N) window beats O(N²) brute force |
Two pointers l, r are naturally moving in one direction | Classic SW motion |
2️⃣ Two Flavors
- Fixed-size window – length stays constant (e.g. every block of size k).
- Variable / dynamic window – you grow and shrink until some condition is satisfied (e.g. no duplicates, sum ≤ target, etc.).
3️⃣ The 4-Step Recipe
(Works for most problems.)
-
Describe the window
• What does left mean? What does right mean?
• What invariant must always hold while the window is “valid”?
-
Expand (right++) until the window first achieves / violates the needed property.
• Update running data (sum, hashmap, deque, etc.) O(1).
-
Contract (left++) only if the window is too large or violates a rule.
• Again update the running data O(1).
-
Record answers on the fly (max length, min length, best sum, etc.).
Rule of thumb: Every element enters and leaves the window at most once → O(N).
4️⃣ Fixed-Size Example: Maximum Sum of K-Length Subarray
Problem: “Given nums and integer k, find max sum of any contiguous subarray of length k.”
def max_sum_k(nums, k):
window_sum = sum(nums[:k]) # 1️⃣ prep first window
best = window_sum
for r in range(k, len(nums)): # r is the NEW element entering
window_sum += nums[r] - nums[r-k] # 2️⃣ add right, remove left
best = max(best, window_sum) # 3️⃣ record
return best
Time O(N), Space O(1).
5️⃣ Variable-Size Example #1: Smallest Subarray With Sum ≥ Target
“Return the min length of a contiguous subarray whose sum ≥ S.”
def min_subarray_len(nums, S):
n = len(nums)
left = 0
window_sum = 0
ans = float('inf')
for right, x in enumerate(nums): # 1️⃣ expand right
window_sum += x
while window_sum >= S: # 2️⃣ shrink while valid
ans = min(ans, right-left+1) # 3️⃣ record
window_sum -= nums[left]
left += 1 # 4️⃣ contract
return 0 if ans == float('inf') else ans
Every element joins/leaves once → O(N).
6️⃣ Variable-Size Example #2: Longest Substring Without Repeating Characters
Input: "abbaabc"
Output: 3 (→ "abc")
We maintain last_pos[ch] (dictionary), and move left past any repeat:
def length_of_longest_unique(s):
last_pos = {} # char -> last index
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last_pos and last_pos[ch] >= left:
left = last_pos[ch] + 1 # jump past the duplicate
last_pos[ch] = right
best = max(best, right - left + 1)
return best
7️⃣ Advanced Window + Data Structure
Sometimes you need “max in window of size k”.
Use a monotonic deque:
from collections import deque
def max_in_each_window(nums, k):
dq = deque() # store indices, nums[dq] is decreasing
out = []
for right, value in enumerate(nums):
while dq and nums[dq[-1]] <= value:
dq.pop() # maintain decreasing
dq.append(right)
if dq[0] <= right - k:
dq.popleft() # left slid past this index
if right >= k - 1: # window ready
out.append(nums[dq[0]])
return out
8️⃣ Common Pitfalls & Pro Tips
🛑 Forgetting to shrink → infinite loop or O(N²).
🛑 Off-by-one: when is window valid vs. invalid? Test tiny cases.
🛑 For variable windows, record answers inside the while loop (when valid) or after expansion (when invalid) — depends on the problem.
💡 Template (Python):
left = 0
for right in range(len(arr)):
# include arr[right] in window
...
while <window invalid>: # or while <window meets 'enough'>:
... # update data to exclude arr[left]
left += 1
# maybe update best/answer here
9️⃣ Practice Problems to Cement the Skill
| Platform | Problem | Fixed / Variable |
|---|
| LeetCode 209 | Minimum Size Subarray Sum | Variable |
| LeetCode 3 | Longest Substring Without Repeating | Variable |
| LeetCode 1004 | Max Consecutive Ones III | Variable |
| LeetCode 76 | Minimum Window Substring | Variable + multiset |
| LeetCode 480 | Sliding Window Median | Fixed + multiset / heaps |
| Educative | Max Sum Subarray of Size K | Fixed |
| Codeforces 279B | Books | Variable |
10️⃣ Quick Checklist Before Coding
☑️ Identify if question involves contiguous chunk.
☑️ Decide fixed vs variable.
☑️ Choose data you need to maintain (sum, counts, deque, heaps).
☑️ Guarantee each element enters & exits once.
☑️ Write tiny hand examples to ensure pointer movement logic.
🎯 Take-away
Slide, don’t loop-inside-loop. Once you view contiguous subarrays as windows, you unlock linear-time solutions to many “would-be” quadratic problems.
Happy sliding! 🛷💨