Sliding Window Technique
The Sliding Window Technique
The sliding window is an algorithmic pattern for processing contiguous subarrays or substrings in O(n) time. Instead of recalculating results from scratch for every possible window position, you maintain a running computation and update it incrementally as the window moves.
Fixed-Size Window
When the problem specifies an exact window size, the pattern is straightforward:
def max_sum_fixed_window(numbers: list[int], window_size: int) -> int:
"""Find the maximum sum of any contiguous subarray of the given size."""
# Initialize with the first window
window_sum = sum(numbers[:window_size])
best_sum = window_sum
# Slide the window: add the new right element, remove the old left element
for right_edge in range(window_size, len(numbers)):
left_edge = right_edge - window_size
window_sum += numbers[right_edge] - numbers[left_edge]
best_sum = max(best_sum, window_sum)
return best_sum
This runs in O(n) because each element is added once and removed once.
Variable-Size Window (Expand/Contract)
When the window size isn't fixed, you use two pointers and dynamically grow or shrink the window:
def longest_substring_without_repeats(text: str) -> int:
"""Find the length of the longest substring without repeating characters."""
left_pointer = 0
longest_length = 0
characters_in_window = set()
for right_pointer in range(len(text)):
current_character = text[right_pointer]
# Contract: shrink window until the repeat is removed
while current_character in characters_in_window:
characters_in_window.remove(text[left_pointer])
left_pointer += 1
# Expand: add the new character
characters_in_window.add(current_character)
# Update best answer
current_window_length = right_pointer - left_pointer + 1
longest_length = max(longest_length, current_window_length)
return longest_length
Why It's O(n), Not O(n^2)
The inner while loop might seem like it makes this quadratic, but count total pointer movements: right_pointer moves forward n times, and left_pointer moves forward at most n times total (it never moves backward). Each element is processed at most twice. Total work: O(2n) = O(n).
This is amortized analysis — the inner loop doesn't run n times per iteration, it runs n times total across all iterations.
The Expand/Contract Mental Model
Think of the window as a caterpillar crawling along the array:
- The right pointer is the head — always moving forward, exploring
- The left pointer is the tail — catches up when the window becomes invalid
- Both pointers only move right — that's what guarantees O(n)
Classic Problems
- Maximum sum subarray of size k (fixed window)
- Longest substring without repeating characters (variable window)
- Minimum window substring (variable, hard — expand to satisfy, contract to minimize)
- Maximum of all subarrays of size k (fixed + monotonic deque)
When to Recognize the Pattern
Ask yourself: "Am I looking at contiguous subarrays/substrings, and can I express the problem as maintaining some property over a window?" If yes, sliding window likely applies.