Two Pointers — the interview technique that wins interviews
Two Pointers — the interview technique that wins interviews
You have two indices. Each moves according to a rule. The input is often sorted (or you sort it first). This one pattern collapses many O(n²) brute-force ideas into O(n).
Three shapes
Opposite ends (converging)
Start at lo = 0, hi = n - 1. Move inward based on a condition.
- Two-sum on sorted array
- Palindrome check
- Container with most water
- 3-sum (fix one, two-pointer on the rest)
Same direction (fast + slow)
Both start at the beginning. One moves faster (or one moves conditionally).
- In-place dedup, in-place remove
- Cycle detection (Floyd's tortoise and hare)
- Find middle of linked list
Two arrays (merge-like)
One pointer per array. Advance the one whose element is smaller.
- Merge two sorted arrays
- Intersection of two sorted arrays
When you can't use it
- Unsorted numeric data where sorting would break the required order → often a hash-map approach instead.
- When you need to remember every past element — that's a stack or a hash map.
Interview trap
Interviewers love: "same problem, but the array is not sorted." Sort it first (O(n log n)) then two-pointer (O(n)). Total: O(n log n) — still often better than the O(n²) brute force.
Try it
- Write
is_palindrome(s: str) -> boolusing two pointers. - Given
nums = [0, 1, 0, 2, 0, 3], move all zeros to the end in-place using same-direction two pointers.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Write
is_palindrome(s)using two converging pointers, case-insensitive. No slicing. Printis_palindrome("Racecar")(True) andis_palindrome("hello")(False). - Exercise 2
Given sorted
nums = [1, 3, 4, 7, 11, 15]andtarget = 18, use converging two pointers to find the pair of indices summing to target. Print the tuple — expected(2, 4). - Exercise 3
Given sorted
nums = [1, 1, 2, 3, 3, 3, 4, 5, 5], dedupe in-place with two same-direction pointers. Store count innew_length. Printnew_lengththennums[:new_length].