Two Pointers & Sliding Window
Many array problems have a slow "check every pair" or "check every subarray" solution and a fast solution that walks through the array with two indexes that only ever move forward (or towards each other). Because each index moves at most n times, these techniques turn O(n²) (or worse) into O(n).
Two pointers from both ends
Problem: in a sorted array, find two values that add up to a target.
The brute force checks every pair, O(n²). With two pointers, start with lo at the smallest value and hi at the largest:
- If
a[lo] + a[hi]is too small, the only way to grow the sum is to moveloright. - If it is too large, move
hileft. - If it equals the target, done.
Each step rules out one value for good, so at most n - 1 steps are needed.
def pair_with_sum(a, target):
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
print(f"a[{lo}] + a[{hi}] = {a[lo]} + {a[hi]} = {s}")
if s == target:
return a[lo], a[hi]
if s < target:
lo += 1
else:
hi -= 1
return None
data = [3, 9, 14, 20, 27, 35, 41, 52]
print("found:", pair_with_sum(data, 66))a[0] + a[7] = 3 + 52 = 55
a[1] + a[7] = 9 + 52 = 61
a[2] + a[7] = 14 + 52 = 66
found: (14, 52)
The same sums appear in the animation. Why is it safe to move hi left when the sum is too big? a[hi] plus even the smallest remaining value is already too large, so a[hi] can't be part of any solution.
Two pointers in the same direction
Two indexes can also move in the same direction: a "slow" one that writes and a "fast" one that reads. Removing duplicates from a sorted array in place:
def dedupe_sorted(a):
write = 1
for read in range(1, len(a)):
if a[read] != a[write - 1]: # a new value: keep it
a[write] = a[read]
write += 1
del a[write:]
return a
print(dedupe_sorted([1, 1, 2, 3, 3, 3, 7, 9, 9]))[1, 2, 3, 7, 9]
Other examples: merging two sorted lists (one pointer per list), checking whether a string is a palindrome (one pointer from each end), and the fast/slow pointers of Floyd's cycle detection in linked lists.
def is_palindrome(text):
chars = [c.lower() for c in text if c.isalnum()]
i, j = 0, len(chars) - 1
while i < j:
if chars[i] != chars[j]:
return False
i, j = i + 1, j - 1
return True
for s in ["Never odd or even", "Was it a car or a cat I saw?", "Two pointers"]:
print(f"{s!r}: {is_palindrome(s)}")'Never odd or even': True
'Was it a car or a cat I saw?': True
'Two pointers': False
Sliding window: fixed size
Problem: find the maximum sum of k consecutive values. Recomputing each window's sum costs O(k), so O(n · k) overall. A sliding window keeps the current sum and updates it when the window moves one step: add the value that enters, subtract the value that leaves.
def best_window(a, k):
s = sum(a[:k])
best, best_start = s, 0
print(f"window 0..{k - 1}: sum {s}")
for start in range(1, len(a) - k + 1):
s += a[start + k - 1] - a[start - 1]
print(f"window {start}..{start + k - 1}: +{a[start + k - 1]} -{a[start - 1]} -> sum {s}")
if s > best:
best, best_start = s, start
return best, best_start
sales = [4, 2, 12, 3, 8, 7, 1, 9]
best, start = best_window(sales, 3)
print(f"best: {best} starting at index {start}: {sales[start:start + 3]}")window 0..2: sum 18
window 1..3: +3 -4 -> sum 17
window 2..4: +8 -2 -> sum 23
window 3..5: +7 -12 -> sum 18
window 4..6: +1 -3 -> sum 16
window 5..7: +9 -8 -> sum 17
best: 23 starting at index 2: [12, 3, 8]
The running sums are the same as in the animation, and so is the winner.
Sliding window: variable size
The window can also grow and shrink. Problem: the shortest run of consecutive values with a sum of at least target. Extend the right end until the sum is large enough, then shrink from the left as long as it stays large enough:
def shortest_at_least(a, target):
left, s, best = 0, 0, None
for right, x in enumerate(a):
s += x # grow to the right
while s >= target: # shrink from the left
if best is None or right - left + 1 < best[1] - best[0] + 1:
best = (left, right)
s -= a[left]
left += 1
return best
data = [2, 3, 1, 2, 4, 3]
lo, hi = shortest_at_least(data, 7)
print(f"shortest run with sum >= 7: {data[lo:hi + 1]} (indexes {lo}..{hi})")shortest run with sum >= 7: [4, 3] (indexes 4..5)
And the classic longest substring without repeating characters, where the window shrinks whenever a character repeats:
def longest_unique(s):
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 # jump past the earlier copy
last_seen[ch] = right
if right - left + 1 > len(best):
best = s[left:right + 1]
return best
for s in ["abcabcbb", "pwwkew", "dataframe"]:
print(s, "->", longest_unique(s))abcabcbb -> abc
pwwkew -> wke
dataframe -> frame
When to reach for these techniques
| Clue in the problem | Technique |
|---|---|
| sorted array, pair or triple with a target sum | two pointers from both ends |
| remove/compact elements in place | slow/fast pointers |
| "consecutive", "subarray", "substring" of fixed length | fixed sliding window |
| "shortest/longest subarray such that …" | variable sliding window |
Test yourself
In the sorted pair-sum problem, what do you do when a[lo] + a[hi] is smaller than the target?
- Move hi left
- Move lo right
- Move both
- Stop: there is no pair
When a fixed-size window slides one step, how is the new sum computed?
- Sum the whole window again
- Add the entering value and subtract the leaving value
- Multiply by k
- Take the maximum
Why are two-pointer algorithms O(n)?
- They use recursion
- Each pointer only moves in one direction, at most n times
- They sort the input
- They use a hash map