Home
DSA Visualizer
Arrays
Two Pointers
Two Pointers
The two pointers technique finds a pair with a specific sum in a sorted array by moving one index from each end toward the other.
TARGET 17 · SORTED
COMPARE
L
0
1
2
3
4
5
6
R
7
2 + 23 = 25, over 17. Nothing left of 23 pairs with it under target — move right in.
Next
2 + 18 = 20, over 17. Nothing left of 18 pairs with it under target — move right in.
Array
Target
Intuition
Instead of using nested loops to check every pair (O(n²)), we can use two pointers starting at the ends of a sorted array to find a pair with a target sum in O(n) time.
Concept
- Sorted Array: Essential for this technique.
- Left Pointer (L): Starts at 0.
- Right Pointer (R): Starts at n-1.
- Logic: If sum < target, we need a larger sum, so move L right. If sum > target, we need a smaller sum, so move R left.
How it Works
Algorithm:
- Initialize
L = 0,R = n - 1. - While
L < R: - Calculate
sum = arr[L] + arr[R]. - If
sum == target, return pair. - If
sum < target, incrementL. - If
sum > target, decrementR.
Step-by-Step Breakdown
Watch the visualization:
- See how the pointers move towards each other.
- Notice that we never check the same pair twice or backtrack.
Trace: sum to 20 in [2, 4, 7, 9, 11, 15]
L=0 R=5
2 + 15 = 17, short of 20. 15 is the largest value in the array, so no right-hand choice can make up the difference — the left value has to grow. Every pair involving 2 is now ruled out.
17 < 20
L=1 R=5
4 + 15 = 19, still short, and by the same argument every pair involving 4 is ruled out.
19 < 20
L=2 R=5
7 + 15 = 22, now over. 7 is the smallest value still in play, so the right value must shrink, and every pair involving 15 is ruled out.
22 > 20
L=2 R=4
7 + 11 = 18, short again. 7 moves on.
18 < 20
L=3 R=4
9 + 11 = 20.
found
the count
Five comparisons, and between them the pointers covered the array once — neither ever moved back, which is what bounds the walk at N steps. A double loop over the same six values would test 15 pairs to reach the same answer, and that gap is N² against N.
5 vs 15
unsorted?
None of the reasoning above survives without sorted order: "the largest value available" is what makes each move forced. On unsorted input the equivalent tool is a hash map of seen values, which is O(N) time and O(N) space.
sorted only
When to Use
- Finding pairs in a sorted array.
- Reversing an array (swapping elements at L and R).
- Partitioning (like in QuickSort).
When NOT to Use
- Unsorted arrays (unless you sort them first).
- When you need to find indices in the original unsorted array (indices change after sorting).
How to Identify
"Find a pair...", "Sorted array", "In-place reversal".
Preparing for interviews? This topic is also taught as a pattern:
Introduction to Two Pointers
Applying for software engineering roles? Free, no sign-up:
