Two Pointers
Reach for it when the problem says
- Sorted input
- pairs that sum to a target
- palindromes
- in-place
- Solved
- 0/31Solved
- Problems
- 31Problems
- Variants
- 5Variants
Problems
5 variantsConverging pointers
0 of 5 solved- Valid PalindromeUp nextSprintDeep diveEasyDecode Valid Palindrome
- Squares of a Sorted ArrayEasyDecode Squares of a Sorted Array
- Valid Palindrome IIEasyDecode Valid Palindrome II
- Container With Most WaterEssentialsSprintDeep diveMediumDecode Container With Most Water
- Trapping Rain WaterSprintDeep diveHardDecode Trapping Rain Water
Same-direction pointers
0 of 9 solved- Move ZeroesEssentialsDeep diveEasyDecode Move Zeroes
- Remove Duplicates from Sorted ArraySprintDeep diveEasyDecode Remove Duplicates from Sorted Array
- Remove ElementSprintDeep diveEasyDecode Remove Element
- Sort Array By ParityEasyDecode Sort Array By Parity
- Length of Last WordSprintDeep diveEasyDecode Length of Last Word
- Remove Duplicates from Sorted Array IISprintDeep diveMediumDecode Remove Duplicates from Sorted Array II
- String CompressionEssentialsDeep diveMediumDecode String Compression
- Rearrange Array Elements by SignMediumDecode Rearrange Array Elements by Sign
- Longest Mountain in ArrayMediumDecode Longest Mountain in Array
Pair sums on sorted input
0 of 8 solved- Two Sum II (Sorted Input)SprintDeep diveMediumDecode Two Sum II (Sorted Input)
- 3SumSprintDeep diveMediumDecode 3Sum
- Max Number of K-Sum PairsEssentialsDeep diveMediumDecode Max Number of K-Sum Pairs
- 3Sum ClosestDeep diveMediumDecode 3Sum Closest
- 4SumDeep diveMediumDecode 4Sum
- Boats to Save PeopleMediumDecode Boats to Save People
- Minimize Maximum Pair Sum in ArrayMediumDecode Minimize Maximum Pair Sum in Array
- Number of Subsequences That Satisfy the Given Sum ConditionMediumDecode Number of Subsequences That Satisfy the Given Sum Condition
Two sequences
0 of 4 solved- Is SubsequenceEssentialsSprintDeep diveEasyDecode Is Subsequence
- Merge Sorted ArraySprintDeep diveEasyDecode Merge Sorted Array
- Merge Strings AlternatelyEssentialsDeep diveEasyDecode Merge Strings Alternately
- Backspace String CompareEasyDecode Backspace String Compare
Reverse and swap
0 of 5 solved- Reverse StringEasyDecode Reverse String
- Reverse Vowels of a StringEssentialsDeep diveEasyDecode Reverse Vowels of a String
- Reverse Only LettersEasyDecode Reverse Only Letters
- Reverse Words in a StringEssentialsSprintDeep diveMediumDecode Reverse Words in a String
- Next PermutationDeep diveMediumDecode Next Permutation
Pattern guide
A nested loop over pairs is O(n²). On 100,000 elements that is ten billion steps, and an interviewer will stop you long before it finishes. Two pointers is the most common way to get that same pair search down to O(n): instead of trying every pair, you keep two indices and use what you just learned to throw away a whole group of pairs with each move.
What it is
A pointer here is just an integer index into a list or string. The pattern keeps two of them and moves them according to a rule, so that every step rules something out for good. Because neither pointer ever moves backward, the total number of moves is at most about 2n.
The classic picture is a sorted list and a target sum. Put left on the smallest value and right on the largest, and let their sum tell you which one to move.
Start at both ends: 1 + 14 = 15, too big. Even the smallest partner is too much for 14, so 14 can never be in the answer.
The key sentence is "this value can never be in the answer". Every two-pointer solution has a version of it. If you cannot say why a move is safe, you do not have a two-pointer solution yet; you have a guess.
nums[L] + nums[R] is too big. Why is it safe to move R left?How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "sorted", "non-decreasing" | Pointers at both ends, moved by comparing with a target |
| "pair", "two numbers", "triplet" that sum to a target | Sort, fix all but two values, two pointers for the last two |
| "in place", "O(1) extra space", "do not return anything" | A read pointer and a write pointer inside the same list |
| "palindrome", "reverse", "mirror" | One pointer at each end, swapping or comparing inward |
| "merge", "subsequence", two strings or two lists | One pointer per input, each moving forward |
| "remove duplicates", "move zeros", "first k elements" | Write pointer marks a kept prefix |
Constraint clues
| Constraint | What it tells you |
|---|---|
n up to 10^5 or 2 * 10^5 | O(n²) is out; O(n) or O(n log n) |
n up to 3000 with "triplets" | O(n²) is expected: sort plus one two-pointer pass per fixed value |
n up to 200 with "quadruplets" | O(n³) is fine: two fixed loops plus a pointer pass |
| "Use O(1) extra space" | Rules out hash maps and copies; points to pointers on the original data |
Values up to 10^9 | A counting array is out, so sorting plus pointers is often the cleanest |
Input and output shape clues
- One sorted list in, a pair or a count out. Converging pointers or pair sums.
- One list in, the same list changed, a length out. Read and write pointers moving in the same direction.
- Two sequences in, one answer out. One pointer per sequence.
- A string in, a string out with some positions swapped. Reverse and swap from both ends.
Looks like it, but isn't
| Neighbour | How to tell them apart |
|---|---|
| Sliding window | Also two indices, but the question is about a contiguous range and its contents ("longest substring with…"). Two pointers usually cares about the two endpoints themselves, or about rearranging. |
| Hash map (Two Sum) | If the input is not sorted and you must return original indices, sorting would scramble them. Use a hash map instead. |
| Binary search | If you need one value, binary search. If you need a pair and the list is sorted, two pointers beats a binary search per element (O(n) vs O(n log n)). |
| Fast and slow pointers on a linked list | Same idea of two speeds, but on nodes, not indices. Cycle detection lives in the linked list pattern. |
The sub-patterns
Converging pointers
When it applies: the answer depends on comparing or combining something near the front with something near the back. Palindromes, the widest container, squares of a sorted list, trapped water. The pointers start at both ends and move toward each other until they meet.
a matches a. Matching pairs never need a deletion, so move both inward.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Each step moves at least one pointer inward. Best-known problems: Valid Palindrome, Container With Most Water, Trapping Rain Water, Squares of a Sorted Array.
Pair sums on sorted input
When it applies: you need two (or three, or four) values whose sum hits, approaches, or stays under a target, and you are allowed to sort. Fix all but two values with loops, then run converging pointers on the rest. The comparison with the target decides which pointer moves.
Sorted. Fix i at -1, so we need L + R = 1. -1 + 2 = 1: a hit, record [-1, -1, 2].
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) for the sort plus O(n) per pass, so O(n) for pairs, O(n²) for triplets, O(n³) for quadruplets. Best-known problems: Two Sum II, 3Sum, 3Sum Closest, Boats to Save People, Number of Subsequences That Satisfy the Given Sum Condition (where a fitting pair contributes 2^(right - left) subsequences at once).
In JavaScript, always pass a comparator to sort: [10, 9, 1].sort() sorts as strings and gives [1, 10, 9].
What does this print?
nums = sorted([1, 5, 2, 4, 3])
left, right = 0, len(nums) - 1
moves = 0
while left < right:
if nums[left] + nums[right] == 6:
break
moves += 1
left += 1
print(nums[left], nums[right], moves)Same-direction pointers
When it applies: you must change one list in place (remove values, compact it, partition it) or scan it in segments. A read pointer visits every element; a write pointer trails behind and marks the end of the part you have finished. Because write never passes read, you never overwrite a value before you have looked at it.
R sees a zero. Zeros are not kept, so only R moves.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Best-known problems: Move Zeroes, Remove Duplicates from Sorted Array, String Compression, Longest Mountain in Array.
The keep rule is the only part that changes between problems. "Keep if not zero", "keep if different from nums[write - 1]", "keep if different from nums[write - 2]" (at most two copies). Compare with the kept prefix, not the raw input, because the input has already been overwritten.
Two sequences
When it applies: there are two inputs (two strings, two sorted lists) and you walk both in order. Each input gets its own pointer, and each pointer only moves forward (or only backward). Merging sorted lists, checking a subsequence, and comparing strings after backspaces all fit.
t[0] is a, which matches s[0]. Advance i to look for b next.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n + m) time, where n and m are the two lengths. Space is O(1) beyond any output. Best-known problems: Merge Sorted Array, Is Subsequence, Backspace String Compare, Merge Strings Alternately.
When the output has to go into one of the inputs (Merge Sorted Array), fill it from the back, where the free space is.
Reverse and swap
When it applies: the output is the input with positions mirrored: a reversed string, reversed vowels, reversed letters only, reversed words, or a reversed suffix. Pointers start at both ends and swap instead of compare. Positions that must not move are skipped by moving only that pointer.
Both pointers sit on letters. Swap a and d.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time. O(1) extra space on a mutable list; O(n) when you must copy an immutable string into a list first. Best-known problems: Reverse String, Reverse Vowels of a String, Reverse Words in a String, Next Permutation.
Next Permutation shows why reverse_range takes a start and an end: after the swap, only the tail to the right of the pivot gets reversed.
What does this print?
nums = [1, 2, 3, 4, 5] left, right = 1, 3 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 print(nums)
A decision checklist
Read the prompt, then ask in order: Is the result a change to one list in place? Are there two separate inputs? Is the answer a mirrored rearrangement? Is there a target sum on sortable data? Otherwise, is it a front-and-back comparison?
Match each problem description to the sub-pattern that fits it best.
Put the steps of the 3Sum solution in order.
- Tap the steps below in the right order.
Traps
<versus<=. Converging loops usually runwhile left < right, because a single element cannot pair with itself. Boats to Save People is the exception: one leftover person still needs a boat, so it runswhile light <= heavy.- Forgetting to sort. Pair-sum logic is only correct on sorted data. Unsorted input with this logic gives answers that look plausible and are wrong.
- Sorting when you must return indices. Sorting scrambles positions. Either carry
(value, index)pairs or use a hash map instead. - Duplicates. In 3Sum and 4Sum, skip repeated values at every level (each fixed loop and the
leftpointer after a hit). Skip too early and you lose answers like[-1, -1, 2]. - Comparing with the input instead of the kept prefix. In read/write problems, earlier slots have been overwritten. Compare with
nums[write - 1]ornums[write - 2]. - Only trying one branch. Valid Palindrome II needs both "skip left" and "skip right" checks. Greedy single-branch versions fail on inputs like
cbbcc. - Writing from the wrong end. When the free space is at the back (Merge Sorted Array), merging from the front overwrites unread values.
- Overflow. Four values near
10^9sum past 32 bits. Python and JavaScript are fine; Java and C++ need 64-bit integers.
Edge cases to always test: an empty list (when allowed), one element, two elements, all values equal, no valid answer, and negatives.
while light <= heavy rather than while light < heavy?How to talk it through
- Converging pointers
- Two indices that start at opposite ends and move toward each other, each step ruling out one element.
- Read and write pointers
- Two indices moving the same direction in one list:
readscans everything,writemarks the end of the finished prefix. - Pair-sum template
- Sort, fix all but two values, then move two pointers inward based on whether the total is below or above the target.
- Elimination argument
- The reason a pointer move is safe: the skipped element cannot be part of any better answer.
- Stable compaction
- Removing elements in place while keeping the survivors in their original order.
- Mirror swap
- Swapping index
iwith indexn - 1 - i, the core of every in-place reversal.