Two Pointers and Sliding Window: From O(n^2) to O(n)
A large family of array and string problems has an obvious O(n^2) solution: try every pair of positions, or every subarray. Two pointers and sliding windows solve many of them in O(n) by moving two indexes through the data in a way that never needs to go backward. The trick is not the code, which is short, but knowing the condition that makes it correct. This guide covers the main shapes of the pattern, the condition behind each, and how to check a fast version against a brute force. Examples use Python 3.10 or later and only the standard library.
Why one pass can replace a double loop
A nested loop over i and j looks at about n^2 / 2 pairs. A two-pointer method looks at far fewer, because each comparison lets it rule out a whole group of pairs at once, and then it moves one index forward (or backward) for good. Since each index moves at most n times in one direction, the total work is O(n), even when there is a loop inside a loop in the code. Every argument below is a version of "this move cannot skip the answer".
Pattern 1: pointers from both ends (sorted input)
Problem: in a sorted list, find two positions whose values add up to a target.
Start with lo at the smallest value and hi at the largest. If their sum is too small, nothing paired with nums[lo] can work: its largest possible partner (the largest remaining value), already falls short. So lo moves right. If the sum is too big, nums[hi] is too large even with the smallest remaining value, so hi moves left. Each step eliminates one value, so the loop runs at most n - 1 times.
Pattern 2: pointers moving the same direction
Problem: remove duplicates from a sorted list in place and return the new length.
A read index visits every element, and a write index marks the end of the unique prefix. When read finds a value different from the last one written, it is copied to write. Both move only forward: O(n) time, O(1) extra space.
def pair_with_sum(nums, target):
"""nums must be sorted in ascending order."""
lo, hi = 0, len(nums) - 1
while lo < hi:
s = nums[lo] + nums[hi]
if s == target:
return lo, hi
if s < target:
lo += 1 # need a bigger sum
else:
hi -= 1 # need a smaller sum
return None
def remove_duplicates(nums):
"""Sorted list: keep one copy of each value in place, return the new length."""
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return write
print(pair_with_sum([1, 2, 4, 7, 11, 15], 15))
print(pair_with_sum([1, 2, 4, 7, 11, 15], 10))
data = [1, 1, 2, 3, 3, 3, 5]
k = remove_duplicates(data)
print(k, data[:k])
(2, 4)
None
4 [1, 2, 3, 5]
For target 15 the pair is at indexes 2 and 4 (4 + 11). For target 10 no pair exists, and the pointers meet and return None. The deduplicated prefix is the first 4 slots.
The same-direction family also includes fast and slow pointers: one index moves two steps for each step of the other. On a linked list, when the fast pointer reaches the end, the slow one is at the middle; if the list has a cycle, the two eventually meet inside it. The linked lists guide uses the trick to find the middle node.
Pattern 3: fixed-size sliding window
Problem: the maximum sum of k consecutive items.
The brute force sums each window from scratch: O(nk). A sliding window keeps the current window's sum and, when it moves one step right, adds the item entering and subtracts the item leaving. Each step is O(1), so the whole scan is O(n).
Pattern 4: variable-size sliding window
Here the window grows on the right one item at a time and shrinks from the left only when it must. Two classic problems:
- Longest substring without repeating characters. Extend
right; if the new character already appears inside the window, moveleftjust past its previous position. A dict remembers where each character was last seen, so the jump is O(1). - Shortest subarray with sum at least a target, for positive numbers. Extend
rightand add to the running total; while the total is at least the target, record the length and drop items from the left.
def max_sum_window(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # slide: add one, drop one
best = max(best, window)
return best
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 repeat
last_seen[ch] = right
best = max(best, right - left + 1)
return best
def shortest_with_sum(nums, target):
"""Positive numbers only. Length of the shortest subarray with sum >= target, or 0."""
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
print(max_sum_window([2, 1, 5, 1, 3, 2], 3))
print(longest_unique("abcabcbb"), longest_unique("pwwkew"))
print(shortest_with_sum([2, 3, 1, 2, 4, 3], 7))
9
3 3
2
In order: the highest-sum window of 3 in [2, 1, 5, 1, 3, 2] is 5 + 1 + 3 = 9; the longest substrings without repeats in "abcabcbb" and "pwwkew" have length 3 ("abc" and "wke"); and the shortest run of [2, 3, 1, 2, 4, 3] reaching 7 is [4, 3], length 2.
The while inside the for in shortest_with_sum looks quadratic, but left only moves forward and can move at most n times in total, across the whole run. So the total work is O(n) plus O(n): linear. This is an amortized argument: count the total movement of each pointer, not the worst case of one iteration.
Why the window needs positive numbers
Shrinking from the left is safe in shortest_with_sum because, with positive numbers, adding an item always raises the sum and removing one always lowers it. Once a window reaches the target, any longer window with the same right end is not needed, and any window that falls below the target can only be fixed by moving right.
A negative number breaks that. In [-5, 3, 3] with target 6, the window adds -5, then 3, then 3, and its total never reaches 6, so it reports no answer. But [3, 3] at the end sums to 6. Dropping the -5 would have raised the total, and the window never considers it, because it only shrinks when the total is already high enough. The test below prints this case on its last line: 0 from the window, 2 from brute force. With negative numbers you need a different method, such as prefix sums with a sorted structure or a monotonic deque.
Check the fast version against brute force
Pointer code is easy to get subtly wrong at the boundaries. The reliable check is to write the obvious O(n^2) or slower version, which is hard to get wrong, and compare the two on many small random inputs:
import random
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
last_seen[ch] = right
best = max(best, right - left + 1)
return best
def longest_unique_brute(s):
best = 0
for i in range(len(s)):
for j in range(i, len(s)):
if len(set(s[i:j + 1])) == j - i + 1:
best = max(best, j - i + 1)
return best
def shortest_with_sum(nums, target):
left = total = 0
best = float("inf")
for right, x in enumerate(nums):
total += x
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
def shortest_with_sum_brute(nums, target):
best = float("inf")
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total >= target:
best = min(best, j - i + 1)
break
return 0 if best == float("inf") else best
random.seed(42)
for trial in range(2000):
s = "".join(random.choice("abcd") for _ in range(random.randint(0, 12)))
assert longest_unique(s) == longest_unique_brute(s), s
nums = [random.randint(1, 9) for _ in range(random.randint(0, 12))]
t = random.randint(1, 40)
assert shortest_with_sum(nums, t) == shortest_with_sum_brute(nums, t), (nums, t)
print("2000 random trials: fast and brute force agree")
# With a negative number the window logic breaks:
print(shortest_with_sum([-5, 3, 3], 6), shortest_with_sum_brute([-5, 3, 3], 6))
2000 random trials: fast and brute force agree
0 2
Small inputs (up to 12 items over a four-letter alphabet or digits 1 to 9) are deliberate: they hit the edge cases, such as empty input, a window that never reaches the target, and repeats right at the boundary, far more often than large random inputs do, and a failure is short enough to read. The fixed random.seed makes a failure reproducible. The same kind of check, run on the other three functions in this guide, also found no disagreement.
Recognizing the pattern
| Clue in the problem | Pattern | Time, extra space |
|---|---|---|
| Sorted array, pair with a target sum | Pointers from both ends | O(n), O(1) |
| Rewrite an array in place, keep some elements | Read and write pointers | O(n), O(1) |
| Middle of a list, cycle in a linked structure | Fast and slow pointers | O(n), O(1) |
| Maximum or minimum over every block of exactly k items | Fixed window | O(n), O(1) |
| Longest or shortest contiguous run with a property that holds for sub-runs (or super-runs) | Variable window | O(n), plus a dict or counter if needed |
If the array is unsorted and you need a pair sum, you have two options: sort first and use two pointers, O(n log n), or use a set of values seen so far, O(n) average time and O(n) space, as in hash tables. The Interview Complexity Estimator's rules table reads these combinations the same way: "sorting" plus "two pointers" in its medium regime gives O(n log n) time and O(n) space, against O(n²) time for "nested loops". Note that its two-pointers row assumes O(1) space; the substring example above also keeps a dict, which is O(n) in the worst case or O(alphabet size).
Check yourself
- Why must the list be sorted for pattern 1? (The decision to move
lorelies onnums[hi]being the largest remaining value.) - Would the fixed-size window work with negative numbers? (Yes. It never decides to shrink; it always adds one item and drops one.)
- How many times can
leftmove in total inlongest_unique? (Its value never exceeds n and never decreases, so the jumps add up to at most n positions.)