What is the sliding window technique?
Keep two pointers marking a range. Extend the right pointer to grow the window, advance the left to shrink it when a constraint breaks. Each element enters and leaves once, so it is O(n).
#Fixed-size window
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] # add one, drop one
best = max(best, window)
return bestInstead of re-summing each window (O(n·k)), update it incrementally: O(n).
#Variable-size window
def longest_unique(s):
seen = {}
left = best = 0
for right, char in enumerate(s):
if char in seen and seen[char] >= left:
left = seen[char] + 1 # shrink past the duplicate
seen[char] = right
best = max(best, right - left + 1)
return bestThe right pointer always moves forward; the left only ever moves forward too. Both traverse the array once, so it is O(n) despite the nested-looking logic.
#When it applies
Look for: contiguous subarray or substring, plus a constraint — longest, shortest, at most k distinct, sum equals target.
- Longest substring without repeating characters
- Minimum window substring
- Maximum sum subarray of size k
- Longest substring with at most k distinct characters
- Permutation in string
#When it does not
Sliding window needs contiguity. If the problem allows skipping elements, you want dynamic programming or a different approach entirely.
It also needs the constraint to be monotonic — shrinking the window must never make it more invalid. With negative numbers, "sum at most k" breaks that property, and prefix sums plus a hash map is the right tool instead.
#Say the name
"This looks like a sliding window — the substring is contiguous and I want the longest one satisfying a constraint." Naming the pattern shows you recognised the shape, which is what the question is testing.