Step 11 Sliding Window / 2 Pointer — Pattern and Template
Theory
Sliding window and two pointers are the standard way to turn O(n^2) 'check every subarray' brute force into a single O(n) pass. The idea: maintain a window [left, right] over the array or string, expand right to include new elements, and shrink left whenever the window breaks the problem's condition. Because each index enters and leaves the window at most once, the whole scan is linear. This lesson covers the fixed and variable window patterns, the state you keep inside the window, and when the technique legally applies.
The core mechanism
You hold two indices, left and right, delimiting a contiguous segment — the window. A driver loop advances right one step at a time, adding arr[right] to some running state (a sum, a frequency map, a count of distinct elements). Whenever the state violates the problem's condition, you advance left, removing arr[left] from the state, until the window is valid again. Every candidate answer is read off from valid windows.
The linearity argument is the thing to internalise: right moves at most n times total, and left also moves at most n times total (it never moves backward). So the loop body executes O(n) times overall, even though it contains a while loop inside a for loop.
Pattern 1: fixed-size window
When the window size K is given, the algorithm is mechanical: build the state for the first K elements, record the answer, then slide — remove the element leaving at the left, add the element entering at the right, record again — until right reaches the end.
Maximum sum of K consecutive elements and 'maximum points from cards' (where the window is the chunk you remove from the middle) are this pattern. Cost is O(n) time and O(1) to O(K) extra space depending on the state kept.
def max_sum_k(arr, k):
window_sum = sum(arr[:k])
best = window_sum
for right in range(k, len(arr)):
window_sum += arr[right] # enter
window_sum -= arr[right - k] # leave
best = max(best, window_sum)
return bestPattern 2: variable window with a validity condition
When the size is not fixed, you expand right greedily and shrink left only while the window is invalid. The state usually includes a frequency map or a set so validity can be checked in O(1).
Worked example — longest substring without repeating characters in 'abcabcbb': expand over a, b, c (window 'abc', length 3). The next a repeats, so shrink from the left, removing a, until the window 'bca' is valid again. Continue: the window slides through 'cab', 'abc', then b repeats twice forcing shrinks to 'cb', then the final b forces 'b'. The maximum length seen is 3. Note the window content and its last-seen positions must be updated on both entry and exit — forgetting the exit update is the most common bug in this pattern.
def longest_without_repeat(s):
seen = {} # char -> count in window
left = 0
best = 0
for right, ch in enumerate(s):
seen[ch] = seen.get(ch, 0) + 1
while seen[ch] > 1: # window invalid
seen[s[left]] -= 1 # remove on exit
left += 1
best = max(best, right - left + 1)
return bestCounting subarrays: the atMost(K) trick
Many problems ask for subarrays with exactly K distinct elements, or sum exactly K, where a direct window cannot stop at 'exactly'. The standard reduction: count subarrays satisfying 'at most K', then answer exactly(K) = atMost(K) - atMost(K - 1). Inside atMost, whenever the window is valid, every subarray ending at right and starting anywhere in [left, right] is valid too, so you add (right - left + 1) to the count instead of just checking one length.
Two pointers on a sorted array is the sibling technique: pointers start at opposite ends and move toward each other based on a comparison (pair with given sum), or one pointer writes while another reads (remove duplicates, move zeroes). Same left/right discipline, different geometry.
When it applies — and common mistakes
Sliding window requires monotonicity: extending the window must move the measured quantity in a predictable direction, and shrinking must be able to restore validity. It works for sums of non-negative numbers, distinctness, and character-frequency conditions. It fails when negatives make sums non-monotonic (use prefix sums + hashing instead) or when the condition involves ordering across the whole array.
Common mistakes: (1) not removing the leaving element from the state when shrinking; (2) using an if instead of a while for shrinking — one removal may not restore validity; (3) recording the answer before the window becomes valid; (4) in fixed-window code, an off-by-one in right - k when choosing the leaving element. Complexities: O(n) time; space O(1) for sums, O(distinct) for frequency states.
Key points
- Each index enters and leaves the window at most once, so expand/shrink scans are O(n) despite the nested while.
- Fixed window: build state for K elements, then add entering / remove leaving on each slide.
- Variable window: expand right, shrink left with a while loop until the validity condition holds again.
- exactly(K) = atMost(K) - atMost(K - 1) is the standard reduction for counting problems.
- Requires monotonic behaviour — negative numbers break sum windows; switch to prefix sums + hashing there.