Two Pointers
How to use two indexes that move through an array to replace nested loops, the three common shapes of the technique, and what interviewers ask about it.
On this page
Two pointers is a technique where you keep two indexes into an array or string and move them according to a simple rule, instead of using a nested loop. It turns many searches over pairs, which take O(n²) time when you try every pair, into a single O(n) pass. You reach for it when the input is sorted, or when you need to rearrange or compare a sequence from both ends.
Take a sorted price list and a gift card worth exactly 16, and suppose you want two prices that add up to it. Without the technique you would check every pair of prices. Because the list is sorted, a single comparison can rule out a whole price at once, and the technique uses that fact to avoid checking most pairs.
How the pair-sum search works
Put one pointer, L, on the smallest price and another, R, on the largest. Add the two prices they point at and compare the sum with the target.
- If the sum equals the target, you have the answer.
- If the sum is too big, move
Rone step left. This is the only move that can make the sum smaller, becauseLis already on the smallest price still in play. - If the sum is too small, move
Lone step right, for the mirror-image reason.
Each step either finds the answer or moves one pointer inward, so the loop runs at most n - 1 times.
L = 0, R = n - 1while L < R: sum = prices[L] + prices[R] if sum == target: return [L, R] if sum > target: R = R - 1 else: L = L + 1return []- prices02L142538411515R
- target
- 16
1
Lstarts on the cheapest price andRstarts on the most expensive. - prices02L142538411515R
- target
- 16
- sum
- 17
22 + 15 = 17, which is too big. Even the cheapest price makes 15 too expensive, so 15 cannot be part of the answer and
Rmoves left. - prices02L142538411R515
- target
- 16
- sum
- 13
32 + 11 = 13, which is too small. Even the largest remaining price is not enough next to 2, so 2 cannot be part of the answer and
Lmoves right. - prices0214L2538411R515
- target
- 16
- sum
- 15
44 + 11 = 15, which is still too small, so
Lmoves right again. - prices021425L38411R515
- target
- 16
- sum
- 16
55 + 11 = 16, which equals the target, so the answer is positions 2 and 4.
- prices02142538411515
- pairs checked
- 4
- all pairs
- 15
6The search checked 4 sums, while trying every pair would have checked up to 15. Each step removed one price for good, shown in grey.
Why discarding a value is safe
Moving a pointer claims that the value it leaves behind cannot be part of any answer, and the technique is only correct when that claim is true. In step 2 above, 2 + 15 was too big. The list is sorted, so every other price is at least 2, which means 15 plus any remaining price is at least 17. The price 15 has no partner, and dropping it loses nothing.
Step 3 is the mirror image. After 15 was dropped, 11 is the largest price in play, so 2 plus any remaining price is at most 13, which is below 16. The price 2 has no partner either.
Code
// prices is sorted from low to high.
// Returns the two positions, or [] if no pair works.
function pairWithSum(prices, target) {
let left = 0;
let right = prices.length - 1;
while (left < right) {
const sum = prices[left] + prices[right];
if (sum === target) return [left, right];
if (sum > target) right--; // too big: drop the largest
else left++; // too small: drop the smallest
}
return [];
}
pairWithSum([2, 4, 5, 8, 11, 15], 16); // [2, 4]# prices is sorted from low to high.
# Returns the two positions, or [] if no pair works.
def pair_with_sum(prices, target):
left, right = 0, len(prices) - 1
while left < right:
total = prices[left] + prices[right]
if total == target:
return [left, right]
if total > target:
right -= 1 # too big: drop the largest
else:
left += 1 # too small: drop the smallest
return []
pair_with_sum([2, 4, 5, 8, 11, 15], 16) # [2, 4]The loop condition is left < right and not left <= right. When the pointers meet they point at the same item, and an item cannot be paired with itself.
Complexity
| Approach | Time | Space | Why |
|---|---|---|---|
| Try every pair | O(n²) | O(1) | About n²/2 sums. |
| Two pointers (already sorted) | O(n) | O(1) | Each step moves a pointer inward, so there are at most n − 1 steps. |
| Two pointers (sort first) | O(n log n) | O(1) to O(n) | Sorting dominates, and the space depends on the sort. |
The three shapes of two pointers
The pair-sum search is one of three common shapes. They differ in where the pointers start and which way they move.
Pointers from opposite ends
This is the shape used for the pair-sum search. The pointers start at the two ends and move toward each other until they meet. It also fits any problem that compares the two ends of a sequence. A palindrome check, for example, compares s[left] with s[right] and moves both inward after each match, stopping at the first mismatch.
The rule for which pointer moves depends on the problem, and it must always be backed by the discard argument above. In the "container with the most water" problem, you compute the area between two vertical lines and then move the pointer on the shorter line. Moving the taller line cannot help, because the area is limited by the shorter line and the width only shrinks.
Two pointers also extends to three values. To find triples that add up to a target, sort the array, fix the first value with an outer loop, and run the pair-sum search on the part of the array to its right. That costs O(n²) in total, compared with O(n³) for three nested loops. When the answer must not contain repeated triples, skip over equal neighbouring values after each step.
Slow and fast pointers on one array
Here both pointers start at the front and move in the same direction. The fast pointer reads every item, and the slow pointer marks where the next item to keep should be written. This rewrites an array in place without allocating a second array. The example below removes repeats from a sorted array and returns how many unique values are left at the front.
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let slow = 0; // nums[0..slow] holds the unique values so far
for (let fast = 1; fast < nums.length; fast++) {
if (nums[fast] !== nums[slow]) {
slow++;
nums[slow] = nums[fast];
}
}
return slow + 1;
}
// [1, 2, 2, 2, 5, 5] becomes [1, 2, 5, ...] and returns 3def remove_duplicates(nums):
if not nums:
return 0
slow = 0 # nums[0..slow] holds the unique values so far
for fast in range(1, len(nums)):
if nums[fast] != nums[slow]:
slow += 1
nums[slow] = nums[fast]
return slow + 1
# [1, 2, 2, 2, 5, 5] becomes [1, 2, 5, ...] and returns 3The same shape solves "move all zeros to the end" and "remove every occurrence of a value". In each case slow is the next free slot, and fast hands it each value that should be kept. The loop looks like it might be quadratic, but neither pointer ever moves backward, so each pointer moves at most n times and the total is O(n).
A related variant uses a slow pointer that moves one step and a fast pointer that moves two, to detect a cycle in a linked list. That is a different idea with a different proof, and it is covered in Linked Lists.
One pointer on each of two sorted lists
With two sorted lists, you keep one pointer in each. At every step you compare the two values they point at, take the smaller one, and advance that pointer. This is how two sorted lists are merged into one in O(n + m) time, and it is the merge step of merge sort. The same walk finds the values two sorted lists have in common: when the two values are equal you record it and advance both pointers, and otherwise you advance the pointer on the smaller value.
function merge(a, b) {
const result = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) result.push(a[i++]);
else result.push(b[j++]);
}
while (i < a.length) result.push(a[i++]);
while (j < b.length) result.push(b[j++]);
return result;
}
// merge([1, 4, 7], [2, 3, 9]) returns [1, 2, 3, 4, 7, 9]def merge(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
# merge([1, 4, 7], [2, 3, 9]) returns [1, 2, 3, 4, 7, 9]When one list runs out, the remaining items of the other list are already sorted, so they are copied to the end without further comparisons.
When two pointers does not apply
The opposite-ends shape needs the discard argument to hold, and for sums that means the data must be sorted. On the unsorted list [8, 2, 15, 4], moving the right pointer left does not necessarily make the sum smaller, so a pointer can skip past a valid pair. There are two ways to handle unsorted input. You can sort it first, which costs O(n log n) and is still better than O(n²). Or you can use a hash map that records the values seen so far, which runs in O(n) time and needs O(n) extra space and does not need sorting at all, as in Matching Receipts.
Two pointers also does not help when the answer depends on a property of a whole range that cannot be updated one item at a time. If the question is about a contiguous stretch with a changing condition, such as the longest stretch with no repeated character, the right tool is the same-direction shape with a running summary, which is called a sliding window. It is covered in Sliding Window.
Pitfalls
In the interview
The signals that a problem wants two pointers are an array or string that is already sorted, a request for a pair or triple that meets a condition, a requirement to modify the array in place with O(1) extra space, or a comparison between the two ends of a sequence. If the statement asks for a pair with a given sum and says nothing about sorting, ask whether the input is sorted, and mention the sort-first and hash map alternatives.
Questions to expect:
- "Why is this correct? Could you skip a valid pair?" No. When the sum is too big, the larger value cannot pair with anything left in the range, because even the smallest remaining value makes the sum too big. The mirror argument holds for the smaller value. Each move therefore discards a value that has no valid partner.
- "What is the time and space complexity?" The time is O(n), because each iteration moves one pointer and the pointers can move at most
n - 1times in total. The space is O(1). If the input is not sorted, the total time is O(n log n) because of the sort. - "The input is not sorted. What do you do?" Either sort first, which costs O(n log n) and may lose the original positions, or use a hash map that stores the values seen so far, which runs in O(n) time and uses O(n) space. The hash map is the better answer when the original positions are needed.
- "How would you extend it to three numbers?" Sort the array, loop over the first number, and run the pair-sum search on the elements to its right. The total time is O(n²). Skip equal neighbouring values so the same triple is not reported twice.
- "How do you modify an array in place with this technique?" Use a
slowpointer for the next write position and afastpointer for reading. The array is rewritten in one pass without a second array, so the space is O(1). - "Does it still work if the array contains negative numbers?" Yes for the pair-sum search, because only the sorted order matters and not the sign. It stops working for problems that rely on all values being positive, such as expanding a window while the sum is too small.
The prices are [3, 5, 9, 14] and the target is 12. L is on 3, R is on 14, and the sum is 17. What should happen next?
Why does the pair-sum search with two pointers need the list to be sorted?
The same-direction version has a for loop over fast, and slow moves inside the loop. What is its time complexity?
What to practise next
Try Squared Deviations, where squaring scrambles the sorted order and two pointers from the ends restores it in one pass. After that, read Sliding Window for problems about contiguous stretches of an array.