Pattern · Interview prep
Two Pointers
Keep two indexes on a sequence and move them by a rule, instead of restarting the scan from every position.
What it is
What is the two pointers pattern?
Two pointers are two indexes that move with a reason. On a sorted row they often start at opposite ends and walk toward each other. Each step throws away a region that cannot hold the answer, so you never pair the current value with every later one.
- Opposite ends. Start at the first and last positions. A sorted pair, or a phrase checked from the outside in, moves one end or both toward the middle.
- Same direction. Both indexes walk forward. One reads the next value, and the other writes the values you keep, as when zeroes slide to the end.
1 + 6 = 7, too small, so the left end moves
When to use it
How do you recognize a two pointers problem?
Read the statement for these signals before you reach for a nested scan.
Read the full recognition guide: Clues that a problem needs two pointers
Read the full recognition guide: Hash map or sorting? How to choose
Phrases to watch for
- sorted array
- pair that sums to
- from both ends
- palindrome
- shrink the range
- move zeroes to the end
- return the indexes
- 1
The input is ordered, or order does not matter
A sorted row tells you which end is too small or too big. If you may sort a copy, the same move still works.
- 2
You want a pair or a comparison of the ends
The answer is two positions, or a check that the outside characters match on the way in.
- 3
One comparison decides one move
Too small means the left value must grow. Too big means the right value must shrink. You do not try both.
Looks similar, but isn’t
A contiguous slice with a running property
If you add one element and drop another while a rule holds, that is a Sliding Window. The ends move in the same direction, not toward a target sum.
An unsorted pair
Without order, a sum that is too small does not tell you which index to move. Remember the complement in a Hash Map.
One boundary in a sorted range
A single index that halves the remaining range is Binary Search. Two pointers keep both ends and move only one of them.
Two speeds on a chain
A linked list has no indexes. One runner steps once and another steps twice. That is Fast and Slow Pointers, not a pair of ends on a sorted row.
Worked example
How does it work on a pair in a sorted array?
The numbers are already sorted. Return the two indexes whose values add up to the target. Exactly one pair exists. This is the classic inward scan, and one of the problems you can practice below.
function pairFromEnds(nums: number[], target: number): [number, number] | null { let left = 0; let right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; // Too small: the left value must grow. Too big: the right value must shrink. if (sum === target) return [left, right]; if (sum < target) left += 1; else right -= 1; } return null;}Each branch moves only one pointer.
Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.
Complexity
- TimeO(n)
Each step moves
leftorrightinward, and neither index moves back. - SpaceO(1)
Only the two indexes are stored. The row is not copied.
A phrase from the outside in
The same walk checks a palindrome. Skip spaces and punctuation, compare the letters without caring about case, and move both ends after a match.
Why the row has to be sorted
Order is what makes one comparison enough. If the values were scrambled, moving the left end would not reliably grow the sum.
Step by step on [1, 2, 4, 6, 8] with target 8
- 1
Start with
lefton1andrighton8. The sum is 9, which is above the target, sorightmoves inward.1L2468R - 2
rightis now on6.1 + 6 = 7, which is below the target, soleftmoves inward. The right end stays put.1L246R8 - 3
leftis on2andrightis still on6.2 + 6 = 8. Return indexes1and3.12468
Common mistakes
What mistakes do people make with two pointers?
Moving both ends after one comparison
A sum that is too small says the left value must grow. Moving the right end at the same time can skip the only pair.
InsteadMove exactly one index. Leave the other where it is until a later comparison says it is wrong.
Sorting away the original indexes
If the problem asks for positions, sorting the row in place renumbers them. The pair you find no longer points at the input.
InsteadSort pairs of value and index, or only use this scan when the row is already sorted and the indexes are the current ones.
Missing the equal case
Treating a sum that matches the target as too small, or too big, walks past the answer and the loop ends empty.
InsteadCheck equality first, then branch. Equal means return. Only a strict difference moves a pointer.
Returning the values instead of the indexes
Several problems want the positions. The values are how you decide the move, not what you hand back.
InsteadReturn `left` and `right` when the sum matches. Check the smaller index is first.
Practice it in Algofily
Which Algofily problems train two pointers?
7 problems are tagged Two Pointers. They run from reversing a string and a sorted pair to a pair of walls.
- Locked: opens after you create an account. Reverse a StringeasyTwo PointersReturn the characters of a string in reverse order.Algofily 40Open problem
- Locked: opens after you create an account. Merge Two Sorted ArrayseasyTwo PointersBoth arrays are sorted in non-decreasing order.Algofily 40Open problem
- Locked: opens after you create an account. Mirror PhraseeasyTwo PointersDecide whether a phrase reads the same forward and backward once spaces, punctuation, and letter case are ignored.Algofily 40Open problem
- Locked: opens after you create an account. Ends of a Sorted ShelfeasyTwo PointersThe integers are already sorted in ascending order.Algofily 40Open problem
- Locked: opens after you create an account. Zeroes to the EndeasyTwo PointersMove every zero in a list to the end while keeping the order of the other numbers.Algofily 40Open problem
- Locked: opens after you create an account. Triples That CancelmediumTwo PointersFind every unique triple of values that adds to zero.Algofily 40Open problem
- Locked: opens after you create an account. Deepest Pair of WallsmediumTwo PointersVertical walls stand on a line.Algofily 40Open problem
A lock means the problem opens after you create an account. Pair With Target is open to try without one.
Start Learning.
Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.