Two Pointer Technique
Table of Contents + β
Say you have a sorted array. Someone asks you to find two numbers that add up to a target. The simple way is to check every pair. That works but it becomes slow quickly. For a big array it does a huge amount of extra work. The two pointer technique fixes exactly this. It walks through the array once. Then it gives you the answer in a single pass.
π€ What Is the Two Pointer Technique?
The two pointer technique is a way to solve array problems with two index variables that move through the data instead of one. A pointer here just means an index. It is a position number in the array.
You place two pointers. Then you move them based on what you see. There are two common styles.
- Opposite ends: one pointer starts at the left. The other starts at the right. They move toward each other.
- Slow and fast: both start near the front. One moves faster than the other.
In this tutorial we focus on the opposite-ends style. It is the one used for the classic pair-sum problem.
π£ The Pain: Why Not Just Check Every Pair?
Here is the problem we want to solve. You are given a sorted array and a target number. You need to find a pair of values that add up to that target.
The first idea most people have is to check every possible pair. You pick one number. Then you loop through the rest to see if any of them completes the sum. That is a loop inside a loop.
The trouble is speed. If the array has n items, two nested loops do about n Γ n checks. That is O(n^2) time. For a small array it feels fine. For an array with a million items it becomes painfully slow.
Caution
The nested-loop approach is O(n^2). It does not use the fact that the array is sorted. So it wastes a lot of work.
π‘ The Idea: Move Two Pointers From Both Ends
Because the array is sorted, we can be smart. Put one pointer left at the start. Put another pointer right at the end. Now look at the sum of those two values.
Here is the spoken logic.
- If the sum equals the target, we found the pair. Done.
- If the sum is too small, we need a bigger number. So move
leftone step to the right. - If the sum is too big, we need a smaller number. So move
rightone step to the left.
See why this works? The array is sorted. So moving left to the right always gives a larger value. And moving right to the left always gives a smaller value. Each step throws away a number we no longer need. We never go back.
Let us trace it on [1, 3, 5, 7, 11] with a target of 12.
| left value | right value | sum | action |
|---|---|---|---|
| 1 | 11 | 12 | equals target, found it |
That one matched right away. Let us look at a target where the pointers have to move. Try the same array with target 10.
| left value | right value | sum | action |
|---|---|---|---|
| 1 | 11 | 12 | too big, move right left |
| 1 | 7 | 8 | too small, move left right |
| 3 | 7 | 10 | equals target, found it |
Notice how few steps that took. We never checked every pair. Each move skipped a whole group of numbers we did not need.
π Steps to Find a Pair With Two Pointers
Here is the plan before we write any code.
- Start
leftat index0, the first element. - Start
rightat the last index, the final element. - While
leftis less thanright, do the checks below. - Find the sum of the values at
leftandright. - If the sum equals the target, return those two positions. You are done.
- If the sum is less than the target, move
leftone step to the right. - If the sum is greater than the target, move
rightone step to the left. - If
leftandrightmeet and you found nothing, there is no such pair.
Note
This only works on a sorted array. If your array is not sorted, sort it first. Or use a different method like a hash set.
π» The Code in 5 Languages
Now let us turn those steps into a function. The function takes a sorted array and a target. It returns the two index positions if a pair is found. If not, it prints a clear message.
# Find a pair that sums to target in a sorted array.def find_pair(arr, target): left = 0 # pointer at the start right = len(arr) - 1 # pointer at the end
while left < right: total = arr[left] + arr[right]
if total == target: print(f"Pair found at index {left} and {right}") return elif total < target: left += 1 # sum too small, need a bigger value else: right -= 1 # sum too big, need a smaller value
print("No pair found")
arr = [1, 3, 5, 7, 11]find_pair(arr, 10)The output of the above code will be:
Pair found at index 1 and 3The values at index 1 and 3 are 3 and 7. They add up to 10. That is our target.
Tip
Both pointers together cross the array only once. So this runs in O(n) time and uses O(1) extra space. That is a big jump from the O(n^2) nested loop.
β±οΈ Complexity Compared
Here is how the two pointer method stacks up against the simple nested-loop idea.
| Approach | Time | Space | Needs sorted input? |
|---|---|---|---|
| Check every pair (nested loops) | O(n^2) | O(1) | No |
| Two pointers from both ends | O(n) | O(1) | Yes |
β οΈ Common Mistakes to Avoid
A few small slips trip people up with this technique.
- Using it on an unsorted array. The whole logic depends on order. On an unsorted array the moves make no sense. Sort it first.
- Writing the loop as
left <= right. With<=you can pair an element with itself, which is usually wrong. Useleft < right. - Moving the wrong pointer. When the sum is too small you move
left, notright. Mixing these up sends the pointers the wrong way. Then you miss the pair. - Forgetting the no-pair case. If the loop ends without a match, return a clear βnot foundβ result instead of leaving the answer empty.
π§© What Youβve Learned
β The two pointer technique uses two moving indices instead of one to scan an array.
β For a pair-sum problem on a sorted array, start one pointer at each end and move them toward each other.
β
Move left right when the sum is too small, and move right left when the sum is too big.
β This turns a slow O(n^2) nested loop into a fast O(n) single pass with O(1) extra space.
β The array must be sorted for the opposite-ends version to work.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Why does the two pointer pair-sum method need a sorted array?
Why: Because the array is sorted, moving left gives a bigger value and moving right gives a smaller one, which makes each pointer move correct.
- 2
The sum at the two pointers is less than the target. What do you do?
Why: A sum that is too small needs a bigger value, so you move the left pointer to the right toward larger numbers.
- 3
What is the time complexity of the two pointer pair-sum method?
Why: Both pointers together cross the array only once, so the work is linear, O(n).
- 4
Why is the loop condition written as left < right and not left <= right?
Why: With left <= right the two pointers can land on the same index, which would pair an element with itself.