Overview
The two-pointer technique keeps two indices into the same sequence and moves them according to a rule. Its power comes from elimination: when the array is sorted and the sum of a[lo] + a[hi] is too small, no pair using a[lo] with anything left of hi can work either, so lo can advance. One comparison rules out a whole row of the brute-force grid.
There are two shapes. Converging pointers start at both ends and move inward (pair sums, palindromes, container with most water). Same-direction pointers move left to right at different speeds (removing duplicates, partitioning, fast/slow cycle detection). Both run in linear time because each pointer only ever moves forward.
Key concepts
Tick a concept once you can explain it in your own words without notes.
Complexity cheat sheet
| Operation | Cost |
|---|---|
| Pair with target sum (sorted) | O(n) vs O(n²) brute force |
| 3Sum | O(n²) after an O(n log n) sort |
| Partition / remove duplicates | O(n) time, O(1) space |
Patterns to recognise
Converging
Use it for: Pair or triplet sums, container with most water, trapping rain water.
Compare, then move the pointer on the side that limits the answer.
Read / write
Use it for: Remove duplicates, remove element, move zeroes.
Copy kept elements to the write index — the array is compacted in place.
Merge two sorted sequences
Use it for: Merge sorted arrays, intersection of sorted lists.
One pointer per sequence; always take the smaller front element.
Code template
def three_sum(nums):
nums.sort()
result = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate anchors
lo, hi = i + 1, len(nums) - 1
while lo < hi:
total = nums[i] + nums[lo] + nums[hi]
if total < 0:
lo += 1
elif total > 0:
hi -= 1
else:
result.append([nums[i], nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1 # skip duplicate seconds
hi -= 1
return result
vector<vector<int>> threeSum(vector<int> nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int n = nums.size();
for (int i = 0; i + 2 < n; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int lo = i + 1, hi = n - 1;
while (lo < hi) {
int total = nums[i] + nums[lo] + nums[hi];
if (total < 0) ++lo;
else if (total > 0) --hi;
else {
result.push_back({nums[i], nums[lo], nums[hi]});
++lo;
while (lo < hi && nums[lo] == nums[lo - 1]) ++lo;
--hi;
}
}
}
return result;
}
Common mistakes
- Converging pointers only work if the data is sorted (or the problem has an equivalent monotonic property).
- Make sure every branch of the loop moves at least one pointer, or you loop forever.
- Sorting destroys original indices — store (value, index) pairs if the answer needs them.
Quick check
Three questions on Two Pointers. Get all three right to earn +15 XP.
-
The opposite-ends two-pointer search for a pair with a given sum needs the array to be:
Sorting is what lets you say "sum too small, move left up" or "too big, move right down".
-
In a sorted array, the two pointers give a sum smaller than the target. What do you do?
Moving left to the right picks a larger number and raises the sum.
-
How does the fast and slow pointer technique detect a cycle?
Fast gains one step per move, so inside a loop it must meet slow.
Challenges
Ordered from easiest to hardest. Solve them on LeetCode, then tick them off here. Know every concept and solve 3 to clear the level.
- Merge Sorted ArrayLeetCode Easy +20
- Remove Duplicates from Sorted ArrayLeetCode Easy +20
- Two Sum II – Input Array Is SortedLeetCode Medium +40
- 3SumLeetCode Medium +40
- Container With Most WaterLeetCode Medium +40
- Sort ColorsLeetCode Medium +40
- Trapping Rain WaterLeetCode Hard +70
Stuck on Two Pointers?Ask Orbi for a hint, a fresh explanation or a review of your code.
Ask the tutor