2.2 Sliding Window
Learn what a Sliding Window is, why re-scanning overlapping subarrays wastes work, and master fixed, variable, and frequency-counted windows.
1. What Is a Sliding Window?
A Sliding Window is a special form of Two Pointers (left and right) that frames a contiguous subarray or substring [left .. right] like a physical window frame sliding across a wall of numbers or characters.
2. Why Do We Need Sliding Window & How Does It Work?
The Pain Without Sliding Window (O(N * K) or O(N^2))
Suppose you have 100,000 numbers and want the highest sum of any 1,000 consecutive numbers.
If you compute sum(nums[0..999]) and then start from scratch to compute sum(nums[1..1000]), you just re-added nums[1..999] (999 numbers!) for no reason.
How Fixed-Size Sliding Window Works (O(N))
When a window of size K shifts 1 step right:
- Add the 1 new item entering on the right (
+ nums[right]). - Subtract the 1 old item leaving on the left (
- nums[right - K]).
How Variable-Size Sliding Window Works (The Caterpillar Rule)
What if the window size isn't fixed—for example, "Find the longest substring with no repeating characters"?
- Expand
right: Steprightforward 1 slot and adds[right]to your window state. - Shrink
leftwhile invalid: If addings[right]broke the rule (e.g., created a duplicate), stepleftforward and removes[left]in awhileloop until the window is valid again. - Update Best: Compare
right - left + 1against your best answer.
Because both left and right only move forward from 0 to N - 1, every item enters the window once and leaves at most once — O(N) total time!
Step Through the Visual Drawing: How a Window Slides in O(1)
Click Next below to watch how the window drops the outgoing left element and adds the incoming right element without re-summing the middle:
Interactive Step-by-Step Trace: Sliding Window (Expand Right, Shrink Left)
Watch how the window slides across [2, 1, 5, 1, 3, 2] without re-summing the middle:
Our first window [2, 1, 5] has sum 8.
3. Basic Operations & Walkthroughs (All 4 Languages)
# 1. Fixed-Size Window: Maximum sum of any subarray of length k
def max_sum_k(nums: list[int], k: int) -> int:
win_sum = sum(nums[:k])
best = win_sum
for right in range(k, len(nums)):
win_sum += nums[right] - nums[right - k]
best = max(best, win_sum)
return best
# 2. Variable-Size Window: Longest Substring Without Repeating Characters
def length_of_longest_substring(s: str) -> int:
last_seen = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last_seen and last_seen[ch] >= left:
left = last_seen[ch] + 1
last_seen[ch] = right
best = max(best, right - left + 1)
return bestUse whenever you need the longest or shortest contiguous subarray/substring satisfying a monotonic condition (no negative numbers in sum problems!).
left = 0
for right, x in enumerate(nums):
add_to_window(x)
while window_breaks_rule():
remove_from_window(nums[left])
left += 1
best = max(best, right - left + 1)| Operation / Pattern | Time | Space | Notes |
|---|---|---|---|
| Fixed-Size Window (Length K) | O(N) | O(1) | 1 addition + 1 subtraction per step |
| Variable-Size Window | O(N) | O(K) | Left and right pointers each move at most N times |
| Anagram / Frequency Window | O(N) | O(1) | Uses fixed 26-slot or 128-slot character frequency array |
5. Practice On Your Own (Curated Submodule Problems)
| Status | Problem | Difficulty | Complexity | Hint? | Links & Notes |
|---|---|---|---|---|---|
Maximum Average Subarray I Fixed-Size Sliding Window | Easy | T: O(N) S: O(1) | |||
Longest Substring Without Repeating Characters Variable-Size Sliding Window | Medium | T: O(N) S: O(min(N, M)) | |||
Longest Repeating Character Replacement String Frequency / Anagram Window | Medium | T: O(N) S: O(1) | |||
Permutation in String String Frequency / Anagram Window | Medium | T: O(N) S: O(1) | |||
Minimum Window Substring Variable-Size Sliding Window | Hard | T: O(N) S: O(1) |