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 and a target sum. Find two numbers that add up to the target.
[1, 3, 4, 6, 8, 11] target = 10
A simple solution checks every possible pair. For each number, compare it with every number after it.
This solution uses two nested loops. Its time complexity is O(N²), where N is the number of values.
However, this solution ignores one important fact: the array is sorted.
Start with the smallest value, 1, and the largest value, 11. Their sum is 12, which is greater than 10.
Because 1 is the smallest value, every other pair that contains 11 will have a sum of at least 12. Therefore, 11 cannot be part of the answer. We can stop considering it.
Next, compare 1 and 8. Their sum is 9, which is less than 10. We now need a larger value. Because 1 is the smallest remaining value, it cannot be part of a valid pair.
Continue this process:
1 + 11 = 12 move the right pointer left
1 + 8 = 9 move the left pointer right
3 + 8 = 11 move the right pointer left
3 + 6 = 9 move the left pointer right
4 + 6 = 10 found the pair
We found the answer without checking every pair.
Core idea
A pointer is an index that shows a position in an array or string.
The Two Pointers pattern uses two indices at the same time. Each pointer moves according to a clear rule.
Every move removes values that cannot be part of the answer. This often replaces two nested loops with one pass through the data.
Sorted order is especially useful. It tells us which pointer to move when a value is too small or too large.
How it works
For the target-sum problem, follow these steps:
- Put the
leftpointer at the first index. - Put the
rightpointer at the last index. - Add
array[left]andarray[right]. - If the sum equals the target, return the two indices.
- If the sum is less than the target, move
leftone step right. This gives us a larger value. - If the sum is greater than the target, move
rightone step left. This gives us a smaller value. - Stop when
leftandrightmeet.
If the pointers meet before finding the target, no valid pair exists.
Let N be the number of values in the array.
At each step, at least one pointer moves. A pointer can move across the array only once. Therefore, the time complexity is O(N).
The algorithm stores only two indices and the current sum. Its extra space complexity is O(1).
The improvement is important:
- Checking every pair takes
O(N²)time. - Two Pointers takes
O(N)time for this sorted pair-sum problem.
Recognize it when
Two Pointers may be useful when you see these signs:
- The input is sorted, or you are allowed to sort it.
- The problem asks for a pair or triplet that meets a condition.
- The problem asks you to change an array in place.
- The problem asks you to use constant extra space.
- Your first solution uses two nested loops over the same array.
- You are comparing two arrays or strings, with one position in each input.
The most useful signal is the nested loop. Ask this question: "Can one pointer replace the inner loop?"
Do not use this basic pattern when:
- The array is unsorted and you must return the original indices. A hash map may be better.
- You need a contiguous part of an array or string that grows and shrinks. Use Sliding Window.
- You need to find a cycle or midpoint in a linked list. Use Fast and Slow Pointers.
- You need to find one specific value in a sorted array. Use Modified Binary Search.
The template
This is the basic template for two pointers that move toward each other:
function findPair(array, target):
left = 0
right = length(array) - 1
while left < right:
sum = array[left] + array[right]
if sum == target:
return [left, right]
if sum < target:
left = left + 1
else:
right = right - 1
return []
Three parts may change in another problem:
- The condition that you test.
- The rule that moves each pointer.
- The value that you return.
The loop structure often stays the same.
The condition left < right also matters. It stops one array value from being paired with itself.
Variants in this chapter
Two pointers do not always start at opposite ends. They can move in several ways.
| Variant | How the pointers move | Problems in this chapter |
|---|---|---|
| Converging | start at opposite ends and move inward | Pair with Target Sum, Squaring a Sorted Array, Minimum Window Sort |
| Same direction | a fast pointer reads and a slow pointer writes | Find Non-Duplicate Number Instances |
| Fixed value plus a pair | one loop fixes a value while two pointers find the remaining values | Triplet Sum to Zero, Triplet Sum Close to Target, Triplets with Smaller Sum, Quadruple Sum |
| Partitioning | pointers divide the array into different regions | Dutch National Flag |
| One pointer per input | one pointer moves through each input | Comparing Strings containing Backspaces |
Start with the converging variant. It makes the main idea easiest to see.
Watch out for
- Moving the wrong pointer. Move the pointer that can bring the result closer to the target.
- Moving both pointers after a failed comparison. You may skip the correct answer.
- Using the wrong stopping condition. Use
left < rightwhen one value cannot be used twice. - Forgetting duplicate values. Skip repeated values when a problem requires unique pairs or triplets.
- Sorting without checking the output requirement. Sorting changes the original indices.
- Ignoring the cost of sorting. Sorting an unsorted array takes
O(N log N)time.
How this compares with nearby patterns
| If the problem needs... | Use... |
|---|---|
| a pair or triplet in a sorted array | Two Pointers |
| a contiguous range that grows or shrinks | Sliding Window |
| a cycle or midpoint in a linked list | Fast and Slow Pointers |
| one specific value in a sorted array | Modified Binary Search |
Two Pointers and Sliding Window both use two indices. The difference is what the indices represent.
With Two Pointers, the indices usually show values that we are comparing. With Sliding Window, the indices show the boundaries of one contiguous range.
Key takeaways
- A pointer is an index that shows a position in an array or string.
- Two Pointers processes two positions at the same time.
- Sorted order often tells you which pointer to move.
- Each move must safely remove values that cannot be part of the answer.
- The pair-sum example improves from
O(N²)time toO(N)time. - The basic pair-sum solution uses
O(1)extra space.
Now apply this pattern to Pair with Target Sum.
Puneeth
· a month 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.
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
Reading Progress
0%
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