Sliding Window Pattern Explained with Python Examples
The sliding window pattern is a way to process a contiguous part of an array or string without starting over for every position. Instead of recomputing, you move the window one step and update only what changed. It turns many O(n²) solutions into O(n).
When should you think of it?
Look for these clues in the problem statement: the word subarray or substring, a request for the longest, shortest or maximum result, and a condition that depends only on the elements inside the current range.
Type 1: fixed-size window
Problem: find the maximum sum of any subarray of length k.
Compute the sum of the first k elements. Then slide one step at a time: add the new element on the right and remove the element that left on the left.
def max_sum_k(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
Each element is added once and removed once, so the time is O(n) and the space is O(1).
Type 2: variable-size window
Problem: find the length of the longest substring without repeating characters.
Keep two pointers, left and right. Expand right one character at a time. If the new character already appears inside the window, move left just past its previous position.
def length_of_longest_substring(s):
last = {} # char -> most recent index
left = best = 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
For abcabcbb the answer is 3 (abc). The last[ch] >= left check matters: it ignores occurrences that are already outside the window.
A reusable template
- Start with
left = 0and looprightover the input. - Add the element at
rightto your window state (sum, counts, set). - While the window breaks the rule, remove the element at
leftand moveleftforward. - Update the best answer using the current window.
Common mistakes
- Forgetting to update the window state when
leftmoves. - Off-by-one errors in the window length. It is
right - left + 1. - Using sliding window when negative numbers break the rule that growing the window only increases the sum.
Practise with problems such as Minimum Size Subarray Sum, Longest Repeating Character Replacement and Permutation in String.