0% completed
Introduction to Two Pointers Pattern
On This Page
Core idea
How it works
Recognize it when
The template
Variants in this chapter
Watch out for
How this compares with nearby patterns
Key Takeaways
You are given a sorted array of numbers and a target sum. Find two numbers in the array that add up to that target.
[1, 3, 4, 6, 8, 11] target = 10
The first approach most people try is to check every pair. Take the first number and compare it against every number after it. Then take the second number and do the same. With N numbers that is about N²/2 comparisons. For an array of 10,000 numbers, that is 50 million comparisons.
Now look at the array again. It is sorted, and the approach above never uses that fact.
Start with the smallest number and the largest number, 1 and 11. They add to 12, which is above the target of 10. Here is the useful part. 1 is the smallest partner that 11 will ever get. If 11 and 1 are already above the target, then 11 with any other number is above it too. So 11 can never be part of the answer, and every pair containing it can be dropped at once.
That is one comparison ruling out five pairs. Repeat the same reasoning and the answer is found in five comparisons instead of fifteen.
Core idea
The Two Pointers pattern keeps two indices into the same array and moves them under a rule. Every move discards a part of the search space that cannot contain the answer. A nested loop that checked every pair becomes a single pass.
The rule is what makes it correct. It normally comes from the array being sorted, because sorted order tells you which direction makes the result larger and which makes it smaller.
How it works
For the pair sum question, the steps are:
- Put
leftat index 0 andrightat the last index. - Add the two values they point at.
- If the sum equals the target, you are done.
- If the sum is below the target, move
leftone step right. Only a larger value can help. - If the sum is above the target, move
rightone step left. Only a smaller value can help. - Stop when the two pointers meet. If they meet without a match, no pair exists.
Each step removes at least one number from consideration, and no number is visited twice. That gives O(N) time, against O(N²) for the nested loops. The pointers are two integers, so the extra space is O(1).
Recognize it when
Use Two Pointers when the question shows these signs.
- The input is sorted, or you are allowed to sort it first.
- You are asked for a pair, a triplet, or a subarray that meets a condition. Common conditions are a target sum, a comparison, or a duplicate rule.
- The question says "in place" or "using constant extra space".
- Your first idea is two nested loops over the same array. This is the most reliable signal of the five. When you notice it, stop and ask whether moving one pointer could replace the inner loop.
- You are comparing two sequences against each other, one pointer in each.
It is not this pattern when:
- The array is unsorted and the question needs the original indices. Sorting destroys them.
- You need a contiguous window whose size or contents change as you scan. That is Sliding Window.
- The data is a linked list and the question asks about a cycle or a midpoint. That is Fast and Slow Pointers.
The template
Almost every problem in this chapter is a variation on this skeleton.
function findPair(array, target):
left = 0
right = length(array) - 1
while left < right:
sum = array[left] + array[right]
if sum == target:
return [left, right] # the condition is met
if sum < target:
left = left + 1 # need a larger value
else:
right = right - 1 # need a smaller value
return [] # the pointers met, nothing found
The skeleton has three decisions. while left < right is the stopping rule. The comparison in the middle is the test. The two moves decide what gets discarded.
For a different problem you change the comparison and change what gets returned. The skeleton stays the same.
Variants in this chapter
The same two pointers move in several different ways. These are the shapes used in this chapter.
| Variant | How the pointers move | Problems in this chapter |
|---|---|---|
| Converging | one at each end, moving inward | Pair with Target Sum, Squaring a Sorted Array, Minimum Window Sort |
| Same direction | a slow writer and a fast reader, editing in place | Find Non-Duplicate Number Instances |
| Fixed value plus a pair | an outer loop fixes one number, two pointers handle the rest | Triplet Sum to Zero, Triplet Sum Close to Target, Triplets with Smaller Sum, Quadruple Sum |
| Partitioning | three pointers split the array into regions | Dutch National Flag |
| One pointer per input | two sequences, one pointer walking each | Comparing Strings containing Backspaces |
Learn the converging variant first. The other four are easier to follow once it is familiar.
Watch out for
- Forgetting to skip duplicates. In the triplet problems the same answer will be produced several times unless you advance past repeated values after a match.
- Using the wrong stopping condition.
left < rightstops before a number is paired with itself.left <= rightallows it. Which one you need depends on the question, so decide it deliberately. - Sorting when you must report original indices. Sort a copy that keeps each value paired with its original index, or use a hash map instead.
- Moving both pointers after a comparison that failed. Only the side that can improve the result should move, otherwise you can skip past the answer.
- Assuming sorted input. If the question does not promise it, sorting costs
O(N log N)and that becomes the real complexity of your solution.
How this compares with nearby patterns
| If the question asks for | Use |
|---|---|
| a pair or triplet in a sorted array | Two Pointers |
| a contiguous subarray or substring that grows and shrinks | Sliding Window |
| a cycle or a midpoint in a linked list | Fast and Slow Pointers |
| one specific value in a sorted array | Modified Binary Search |
Sliding Window is the pattern most often confused with this one, and it is the same idea under a different rule. There, both pointers move in one direction and the region between them is the answer. Here they move toward each other and the region between them is what is left to search.
Key Takeaways
- Two Pointers replaces a nested loop with a single pass, taking
O(N²)down toO(N). - It works because sorted order tells you which pointer to move.
- Every move must discard values that cannot be part of any answer. If a move cannot justify that, the pattern does not apply.
- The skeleton is fixed. The comparison and the return value are what change between problems.
- Extra space stays
O(1), which is often the reason this pattern is the expected answer.
Let's apply it to the first problem, Pair with Target Sum.
Hajin Kim
· 2 years ago
It would be awesome if I could just write up notes on the side of each material so I can refer back to it
surbhi
· 4 years ago
Hello, Are there any patterns for solving String related questions?
Mohammad Awad
· 4 years ago
hi
Puneeth
· 20 days ago
Two pointers technique is useful whenever we have a set of elements let's say a pair, a triplet or even a subarray given we have a sorted array and we have to fulfil certain constraints.
On This Page
Core idea
How it works
Recognize it when
The template
Variants in this chapter
Watch out for
How this compares with nearby patterns
Key Takeaways