Two Pointers

In short: The two-pointer technique walks through an array, string, or linked list with two indexes at once, moving each one based on what they point to. The common shapes are pointers at opposite ends moving toward each other, a slow and a fast pointer moving the same way, and fast and slow pointers on a linked list. It often turns an O(n²) check-every-pair solution into an O(n) one with O(1) extra space.

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 right one step left, to a cheaper cake.
  • Too small? Move left one 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:

// returns the indexes of two numbers that add up to target, or null if there aren't any public static int[] findPairWithSum(int[] sortedNums, int target) { int left = 0; int right = sortedNums.length - 1; while (left < right) { int pairSum = sortedNums[left] + sortedNums[right]; if (pairSum == target) { return new int[] {left, right}; } if (pairSum < target) { // sortedNums[left] is too small even with the biggest number // that's left, so no pair that uses it can work left++; } else { // sortedNums[right] is too big even with the smallest number // that's left, so no pair that uses it can work right--; } } return null; // no two numbers add up to target } // findPairWithSum(new int[] {1, 3, 4, 6, 8, 11}, 10) returns {2, 3}: 4 + 6 // findPairWithSum(new int[] {1, 3, 4, 6, 8, 11}, 13) returns null

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.

public static int maxWater(int[] heights) { int left = 0; int right = heights.length - 1; int best = 0; while (left < right) { int width = right - left; best = Math.max(best, width * Math.min(heights[left], heights[right])); // the shorter wall caps the water level. any other container that // uses it would be narrower and no taller, so move past it if (heights[left] < heights[right]) { left++; } else { right--; } } return best; } // maxWater(new int[] {3, 8, 2, 5, 7, 1}) returns 21: the walls at indexes 1 and 4, 3 apart and 7 tall

More opposite-ends problems

  • Reversing in place. Swap the items at left and right, 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:

public static int removeDuplicates(int[] sortedNums) { if (sortedNums.length == 0) { return 0; } int write = 1; // sortedNums[0..write - 1] holds the distinct values we've kept so far for (int read = 1; read < sortedNums.length; read++) { // keep sortedNums[read] only if it's different from the last value we kept if (sortedNums[read] != sortedNums[write - 1]) { sortedNums[write] = sortedNums[read]; write++; } } return write; // the new length: sortedNums[0..write - 1] has no duplicates } // for {1, 1, 2, 3, 3, 4}, removeDuplicates returns 4, and the array starts with {1, 2, 3, 4}

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 slow one node per step and fast two. When fast reaches the end, slow has gone half as far, so it's at the middle. In Angel Food → Bundt → Cheese → Devil's Food → Eccles, fast visits Angel Food, Cheese, and Eccles while slow visits Angel Food, Bundt, and Cheese, the middle.
  • Cycle detection (Floyd's tortoise and hare). Use the same two speeds. If the list ends, fast reaches the end and there's no cycle. If the list loops back on itself, both pointers end up going around the loop forever, and fast gains one node on slow every step. So the gap between them shrinks by exactly one each step, and fast lands on slow instead of jumping over it.
public class LinkedListNode { public String value; public LinkedListNode next; public LinkedListNode(String value) { this.value = value; } } public static LinkedListNode middleNode(LinkedListNode head) { // slow moves 1 node per step and fast moves 2, so when fast // reaches the end, slow is halfway down the list LinkedListNode slow = head; LinkedListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; // with an even number of nodes, this is the second of the two middles } public static boolean hasCycle(LinkedListNode head) { // Floyd's tortoise and hare LinkedListNode slow = head; LinkedListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { return true; // fast caught up with slow from behind, so the list loops } } return false; // fast reached the end of the list } // for Angel Food -> Bundt -> Cheese -> Devil's Food -> Eccles: // middleNode returns the Cheese node, and hasCycle returns false // if Eccles points back to Cheese, hasCycle returns true

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 <= right instead of left < 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.next before fast.next.next. Depending on whether the list has an odd or even number of nodes, fast ends up either on the last node (whose next is null) or on null itself. Check both fast and fast.next in the loop condition before moving fast two 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:

Frequently Asked Questions

What is the two-pointer technique?

It means walking an array, string, or linked list with two indexes or node references at once: usually one at each end moving toward the middle, or a slow one and a fast one moving the same way. It solves problems like finding a pair with a given sum in a sorted array, reversing in place, and detecting a cycle in a linked list in O(n) time and O(1) extra space.

Why does the two-pointer technique work on a sorted array?

If the two items add up to too much, the right item is too big even with the smallest item still in play, so no pair that uses it can work and you can drop it. If the sum is too small, the same reasoning drops the left item. Each step rules out every remaining pair for one item, so you never skip the answer.

What is the time complexity of the two-pointer technique?

Usually O(n) time and O(1) extra space, because each pointer only moves in one direction and moves at most n times. If the input has to be sorted first, sorting adds O(n log n) time.

What are fast and slow pointers?

Two pointers that walk a linked list at different speeds, usually two nodes and one node per step. When the fast one reaches the end, the slow one is at the middle. If the list has a cycle, the fast one catches up with the slow one instead, which is Floyd's tortoise and hare cycle detection.

What's the difference between two pointers and a sliding window?

A sliding window is a kind of two-pointer technique where both pointers move in the same direction and everything between them matters, like a running sum or a count of characters. Other two-pointer techniques often start at opposite ends of a sorted array and look only at the two items the pointers are on.

Should I use two pointers or a hash map to find two numbers with a target sum?

If the array is sorted, two pointers find a pair in O(n) time and O(1) space. If it's unsorted, a hash set or hash map finds one in O(n) time and O(n) space, while sorting first to use two pointers costs O(n log n) time and loses the original indexes unless you keep them alongside the values.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .