Quick reference
The two-pointer technique walks through an array, a string, or a linked list with two indexes (or node references) at once, moving each one based on what they point to. It often turns an O(n²) "check every pair" solution into an O(n) one that uses only O(1) extra space.
Three common shapes:
- Opposite ends: one pointer starts at each end and they move toward each other. Used for pairs in a sorted array, palindrome checks, and reversing in place.
- Same direction: a slow pointer and a fast pointer both move left to right, like a "write" pointer trailing a "read" pointer to remove duplicates in place, or one pointer in each of two sorted arrays to merge them.
- Fast and slow on a linked list: one pointer moves two nodes per step and the other moves one. Used to find the middle node and to detect a cycle.
Cost:
- Usually O(n) time, because each pointer only moves one way and moves at most n times, and O(1) extra space. If the input has to be sorted first, add O(n log n) for the sort.
When to Use Two Pointers
Reach for two pointers when you see one of these signals:
- The input is sorted (or you can afford to sort it), and you're looking for a pair or a triple that adds up to a target, or that's closest to one.
- You need to compare or swap items from both ends: checking whether a string is a palindrome, or reversing something in place.
- You need to rearrange items in place with O(1) extra space: remove duplicates, remove every copy of a value, or move all the zeros to the end.
- You're merging or comparing two sorted sequences.
- You're working with a linked list and need a position you can't jump to directly, like the middle node or the kth to last node, or you need to know whether it loops back on itself.
The common thread: a brute-force solution would try every pair of positions, but some fact about the input (it's sorted, or a linked list only goes forward) tells you which pointer to move, so you can rule out most pairs without ever looking at them.
Opposite Ends: Pointers That Move Toward Each Other
Example problem: your bakery's cake prices, sorted from cheapest, are [1, 3, 4, 6, 8, 11]. A customer has a $10 gift card and wants two different cakes that use it up exactly. Which two?
Checking every pair takes O(n²) time.
Instead, put a left pointer on the cheapest cake and a
right pointer on the most expensive one, and look at
their sum:
-
Too big? Move
rightone step left, to a cheaper cake. -
Too small? Move
leftone step right, to a pricier cake. - Just right? Done.
| Left (price) | Right (price) | Sum | Compared with 10 | Move |
|---|---|---|---|---|
| 0 ($1) | 5 ($11) | 12 | Too big | Right pointer left |
| 0 ($1) | 4 ($8) | 9 | Too small | Left pointer right |
| 1 ($3) | 4 ($8) | 11 | Too big | Right pointer left |
| 1 ($3) | 3 ($6) | 9 | Too small | Left pointer right |
| 2 ($4) | 3 ($6) | 10 | Match | Return indexes 2 and 3 |
Five steps instead of checking all 15 pairs:
Why it works
It can look like we're skipping pairs and might miss the answer. We're not. Look at the first step: $1 + $11 = $12 is too much. The $1 cake is the cheapest one still in play, so the $11 cake is too expensive to pair with any of the cakes that are left. Every pair that uses it is ruled out, so we can drop it. That one step crossed off a whole row of pairs ($11 with $1, $3, $4, $6, and $8), not just one.
The same goes the other way. When the sum is too small, the left cake is too cheap even with the most expensive cake that's left, so every pair that uses it is too small. Each step drops one cake and every pair it's part of, so after at most n - 1 steps the pointers meet, and every pair has either been checked or ruled out. That's why it takes O(n) time.
This only works because the array is sorted. On unsorted input, "too big" doesn't tell you which pointer to move.
Container with the most water
Another classic: given the heights of some vertical walls, standing 1 unit apart, which two walls hold the most water between them? The water is as wide as the gap between the walls and as tall as the shorter wall. The input isn't sorted, but a similar argument still tells us which pointer to move.
Start with the two outermost walls. Say the left one is shorter. Every other container that uses it has its right wall further in, so it's narrower, and its water still can't rise above the left wall. None of them can beat the one we just measured, so we can drop the left wall and move that pointer in. In general: always move the shorter wall.
More opposite-ends problems
-
Reversing in place. Swap the items at
leftandright, move both pointers one step toward the middle, and stop when they meet. Practice it with Reverse String in Place, then Reverse Words, which uses the same swap on part of a string. - Palindrome check. Compare the first and last characters, move both pointers inward, and repeat. If any pair doesn't match, it's not a palindrome.
- Three numbers that add up to a target (3Sum). Sort, then for each number, run the pair search above on the numbers after it. That's O(n²) time instead of O(n³) for checking every triple.
Same Direction: Read and Write Pointers
Here both pointers start at the beginning and move right, but at different speeds. A read pointer looks at every item, and a write pointer marks where the next item we want to keep should go. The write pointer never gets ahead of the read pointer, so we can overwrite the array as we go, with no second array.
Example problem: remove the duplicates from a sorted array in place, and return how many distinct values are left.
Since the input is sorted, copies of a value sit next to each other.
So an item is new exactly when it's different from the last value we
kept. For [1, 1, 2, 3, 3, 4], the first item is always kept, so
write starts at 1:
| Read | Item | Last kept | Keep it? | Write (after) | Array (after) |
|---|---|---|---|---|---|
| 1 | 1 | 1 | No, it's a copy | 1 | [1, 1, 2, 3, 3, 4] |
| 2 | 2 | 1 | Yes: copy it to index 1 | 2 | [1, 2, 2, 3, 3, 4] |
| 3 | 3 | 2 | Yes: copy it to index 2 | 3 | [1, 2, 3, 3, 3, 4] |
| 4 | 3 | 3 | No, it's a copy | 3 | [1, 2, 3, 3, 3, 4] |
| 5 | 4 | 3 | Yes: copy it to index 3 | 4 | [1, 2, 3, 4, 3, 4] |
The first 4 items are now [1, 2, 3, 4]. Whatever's after them is leftover and doesn't matter, which is why the method returns the new length:
The same read/write shape handles "remove every copy of a value" (keep an item if it's not that value) and "move all the zeros to the end" (write every nonzero item, then fill the rest with zeros).
One pointer in each of two sorted arrays
To merge two sorted arrays, keep a pointer into each one. At every step, take the smaller of the two current items and move that pointer forward. When one array runs out, copy over the rest of the other. That's O(n) time, plus O(n) space for the merged result. It's the merge step of merge sort, and you can practice it with Merge Sorted Arrays. Cafe Order Checker runs the same idea in reverse: it walks a pointer through each of three arrays to check whether the kitchen's served orders could be the two registers' orders interleaved, with each register's orders still in order.
Fast and Slow Pointers on a Linked List
You can't jump to the middle of a linked list the way you can with an index. But two pointers moving at different speeds, both starting at the head, can tell you a lot:
-
Middle node. Move
slowone node per step andfasttwo. Whenfastreaches the end,slowhas gone half as far, so it's at the middle. In Angel Food → Bundt → Cheese → Devil's Food → Eccles,fastvisits Angel Food, Cheese, and Eccles whileslowvisits Angel Food, Bundt, and Cheese, the middle. -
Cycle detection (Floyd's tortoise and hare).
Use the same two speeds. If the list ends,
fastreaches the end and there's no cycle. If the list loops back on itself, both pointers end up going around the loop forever, andfastgains one node onslowevery step. So the gap between them shrinks by exactly one each step, andfastlands onslowinstead of jumping over it.
Both methods take O(n) time and O(1) space. For cycle detection, the alternative is to store every node you visit in a hash set and stop when you see one again, which is also O(n) time but costs O(n) space. Practice it with Does This Linked List Have a Cycle?
Pointers with a fixed gap
A close cousin moves both pointers at the same speed, but with a head start. To find the kth to last node, start one pointer at the head and move another to the kth node, so it's k - 1 nodes ahead. Then move both one node at a time. When the leading pointer reaches the last node, the trailing one is the kth to last node. That's Kth to Last Node in a Singly-Linked List, and its solution points out a subtlety: this "one pass" takes about the same number of steps as counting the nodes first and then walking to the target.
Find Repeat, Space Edition BEAST MODE uses a fixed gap to find where a cycle starts, on an array. It treats each value as a pointer to another position, so the array acts like a linked list with a cycle. It measures the cycle's length, then starts one pointer that many steps ahead of the other and moves both one step at a time until they meet at the first node of the cycle. That node's position is a repeated number.
Two Pointers Time and Space Complexity
A two-pointer loop can look like it does a lot of work, but each pointer only ever moves one way (forward, or inward), and it can't move more than n times. So the loop runs at most about 2n times, doing O(1) work each time: O(n) time. The only extra memory is a few indexes, so it's O(1) space.
| Problem | Without two pointers | With two pointers |
|---|---|---|
| Pair with a target sum in a sorted array | O(n²) time checking every pair, or O(n) time and O(n) space with a set | O(n) time, O(1) space |
| Container with the most water | O(n²) time checking every pair of walls | O(n) time, O(1) space |
| Remove duplicates from a sorted array | O(n²) time shifting items left for each copy, or O(n) space for a new array | O(n) time, O(1) space |
| Detect a cycle in a linked list | O(n) time and O(n) space with a set of visited nodes | O(n) time, O(1) space |
If the input isn't sorted and the technique needs it to be, sorting first costs O(n log n) time, which then dominates. For more on counting steps like this, see our big O notation guide.
Two Pointers vs. Sliding Window vs. Hash Map
A sliding window is a special kind of two-pointer technique, and a hash map is the usual alternative when two pointers don't apply. Here's how to choose:
| Two pointers (opposite ends) | Sliding window | Hash map or set | |
|---|---|---|---|
| How it works | Start at both ends and move inward, based on the two items the pointers are on | Both pointers move left to right, and you keep a running summary of everything between them | One pass, remembering what you've already seen |
| Typical input | A sorted array, or anything you're reversing or checking from both ends | Any array or string, when the answer is a contiguous range | Anything, sorted or not |
| Extra space | O(1) | O(1) for a running sum, more for counts or a set | O(n) |
| Time | O(n), plus O(n log n) if you have to sort first | O(n) | O(n) |
| Typical problems | Pair with a target sum in a sorted array, container with the most water, palindrome checks, reversing in place | Longest substring without repeating characters, maximum sum of k numbers in a row | Two numbers with a target sum in an unsorted array, counting, finding repeats |
For "find two numbers that add up to a target," the choice depends on the input:
- Already sorted: use two pointers. O(n) time and O(1) space.
- Unsorted: use a hash set (or a hash map, if you need indexes): for each number, check whether target minus that number is already in it. O(n) time and O(n) space. Sorting first so you can use two pointers costs O(n log n) time and scrambles the original indexes, unless you sort (value, index) pairs.
Our Inflight Entertainment question is the unsorted version, solved with a set. Its bonus question asks what changes if the movie lengths are sorted, which is a good place to try two pointers.
Common Two-Pointer Mistakes
-
Using opposite-end pointers on unsorted input. The pair search only works because a sum that's too big tells you the right pointer is too big. Sort first, or use a hash set.
-
left <= rightinstead ofleft < right. When the pointers meet, they're on the same item. For a pair search, letting them meet would pair an item with itself: [5] with a target of 10 would "find" 5 + 5. -
Not checking
fast.nextbeforefast.next.next. Depending on whether the list has an odd or even number of nodes,fastends up either on the last node (whosenextis null) or on null itself. Check bothfastandfast.nextin the loop condition before movingfasttwo steps. -
Moving both pointers, or neither. In a pair search, each step should move exactly one pointer, the one that's ruled out. Moving both can skip the answer, and moving neither loops forever.
-
Reporting duplicate answers. When you want every pair or triple (as in 3Sum), skip over repeated values after you use one, or you'll report the same combination more than once.
-
Reading the leftovers. After a read/write pass, only the items before the write pointer mean anything. Return the new length and use just that part.
Classic Two-Pointer Problems
Opposite ends:
- Pair with a target sum in a sorted array (and 3Sum, which runs it once per number).
- Container with the most water. Always move the shorter wall.
- Reverse a string in place. Swap from both ends toward the middle. Practice: Reverse String in Place.
- Reverse the words in a message. Reverse the characters between a left and a right index, first for the whole message and then for each word. Practice: Reverse Words.
- Palindrome check. Compare characters from both ends.
Same direction:
- Remove duplicates from a sorted array, remove a value, or move the zeros to the end, in place. A write pointer trails a read pointer.
- Merge two sorted arrays. One pointer in each. Practice: Merge Sorted Arrays, then Cafe Order Checker, which keeps a pointer in each of three arrays.
Linked lists:
- Detect a cycle. Fast and slow pointers. Practice: Does This Linked List Have a Cycle?
- Find the middle node. Fast and slow pointers.
- Find the kth to last node. Two pointers with a fixed gap. Practice: Kth to Last Node in a Singly-Linked List.
- Find a repeated number in O(n) time and O(1) space. Treat an array like a linked list and find where its cycle starts. Practice: Find Repeat, Space Edition BEAST MODE.
Two Pointer interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
- Reverse String in Place » Write a function to reverse a string in place.
- Does This Linked List Have A Cycle? » Check whether a singly linked list has a cycle, using only O(1) additional space. A classic coding interview question, with a step-by-step solution.
Your first 3 questions are free. Just sign in, no credit card. More Two Pointer questions
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake