Two pointers
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Two pointers means keeping two markers on a list, often at both ends, and moving them towards each other or in the same direction based on a simple test. It replaces a slow check of every pair with one quick pass, especially on sorted data.
Practical use cases
- Web app: Finding two items that add up to a voucher. A shopping page lets a user with a 1,000 rupee voucher find two items whose prices add up to exactly that. With prices sorted, one marker starts at the cheapest and one at the dearest of the available items. If the sum is too high, move the right marker down; if too low, move the left marker up. The pair appears in one pass.
- Web app: Removing duplicates from a sorted list. A mailing-list page cleans a sorted list of 200,000 emails. One marker reads ahead while another marks where the next unique email goes. A single pass squeezes out the duplicates in place, with no second big list. Memory stays small and the cleanup finishes in a blink, not minutes.
- System: Merging sorted lists. Databases and search engines merge two sorted lists of results by keeping a marker in each and always taking the smaller front item. This is also how merge sort combines its halves, and it never goes backwards. Each list is read only once from start to end, so merging a million results stays fast and needs no extra sorting afterwards.
The story: Two Friends and the Gift Shelf
Aarav and Zoya had exactly ₹14 to buy a gift for their teacher, and they wanted to spend all of it on two items. The shop shelf had prices arranged from cheapest on the left to costliest on the right.
The first idea: pick one item, then compare it with every other item. That would take forever. Zoya had a better plan. "I'll stand at the cheapest end and you stand at the costliest end. Add our two prices."
Too much? The one holding the pricier item steps inward to a cheaper one. Too little? The one holding the cheaper item steps inward to a pricier one. In just a few steps, they met the perfect pair. No item was ever checked twice.
How to spot this problem, and where you need it
You are comparing pairs of items in a sorted or two-ended list, and the nested loops that check every pair make the code unbearably slow for large inputs.
Signs you need it
- The data is sorted, and the problem asks for a pair, triple or palindrome check involving both ends.
- You have two loops, one inside the other, that both go across the same array looking for a combination.
- You need to merge two sorted lists, or remove duplicates, or partition without extra memory.
Where to use it in a project
- Price, budget and voucher matching features that need two items adding to a target.
- Data cleanup and merging jobs: deduplicating sorted records, joining two sorted exports, or checking palindromic codes.
The solution
Place one pointer at the start and one at the end, or both at the start for same-direction work. Compare what they point at. Based on the result, move exactly one pointer: for a sum that is too big, move the right one left; too small, move the left one right. Each pointer only moves one way, so together they cross the list just once.
Payoff: Before: checking every pair, about 5 million checks for 3,000 prices. After: about 3,000 steps, finishing instantly.
Explain it like I am 8
You and a friend start at opposite ends of a line of numbers, sorted small to big. If your two numbers add up to too much, the right-hand friend moves left to a smaller number. If too little, the left-hand friend moves right to a bigger one. Keep going until they match or bump into each other.
How it works, step by step
- Sort first (or make sure it is already sorted). The whole trick depends on the order.
- Put one pointer at each end.
left = 0,right = n - 1. - Compare the sum to the target. Equal: found. Too big:
right--. Too small:left++. - Stop when they cross. If they meet without a match, no such pair exists.
The code in four languages
PHP
<?php
// Sorted prices; find two that add up to $target
function pairWithSum(array $prices, int $target): ?array {
$left = 0;
$right = count($prices) - 1;
while ($left < $right) {
$sum = $prices[$left] + $prices[$right];
if ($sum === $target) return [$prices[$left], $prices[$right]];
if ($sum > $target) $right--; // too much: bring in a cheaper item
else $left++; // too little: bring in a pricier item
}
return null; // pointers crossed: no pair
}
print_r(pairWithSum([1, 3, 4, 6, 8, 11, 15], 14)); // [3, 11]JavaScript
// Sorted prices; find two that add up to target
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 [prices[left], prices[right]];
if (sum > target) right--; // too much: bring in a cheaper item
else left++; // too little: bring in a pricier item
}
return null; // pointers crossed: no pair
}
console.log(pairWithSum([1, 3, 4, 6, 8, 11, 15], 14)); // [3, 11]Java
import java.util.*;
public class Main {
// Sorted prices; find two that add up to target. Returns null if there is no pair.
static int[] pairWithSum(int[] prices, int target) {
int left = 0;
int right = prices.length - 1;
while (left < right) {
int sum = prices[left] + prices[right];
if (sum == target) return new int[]{prices[left], prices[right]};
if (sum > target) right--; // too much: bring in a cheaper item
else left++; // too little: bring in a pricier item
}
return null; // pointers crossed: no pair
}
public static void main(String[] args) {
int[] prices = {1, 3, 4, 6, 8, 11, 15};
System.out.println(Arrays.toString(pairWithSum(prices, 14))); // [3, 11]
}
}Go
package main
import "fmt"
// pairWithSum looks for two sorted prices that add up to target.
func pairWithSum(prices []int, target int) (int, int, bool) {
left, right := 0, len(prices)-1
for left < right {
sum := prices[left] + prices[right]
if sum == target {
return prices[left], prices[right], true
}
if sum > target {
right-- // too much: bring in a cheaper item
} else {
left++ // too little: bring in a pricier item
}
}
return 0, 0, false // pointers crossed: no pair
}
func main() {
prices := []int{1, 3, 4, 6, 8, 11, 15}
a, b, ok := pairWithSum(prices, 14)
fmt.Println(a, b, ok) // 3 11 true
}Time: O(n) · Extra space: O(1). Each pointer only moves one way, so together they make at most n moves.
Watch out for
- Using it on an unsorted list. The "too big / too small" logic only works when the data is ordered.
- Using
left <= rightfor pair problems. That lets one item pair with itself.
Quick check
- The two friends' sum is too big. Who moves?
- Left friend moves right
- Right friend moves left
- Both stay
- What must be true about the list?
- It must be sorted
- It must have an even length
- It must contain no duplicates
- Compared with checking every pair, two pointers goes from O(n²) to…
- O(n)
- O(1)
- O(log n)