Lesson 6 of 40Core patterns
Two Pointers
Walk two indices through an array, from both ends or at two speeds, to solve pair and in-place problems in O(n).
Many array problems look like they need every pair of elements, which is O(n²). Two pointers solves a big family of them in a single pass with O(1) extra memory. It shows up constantly in interviews ("pair in a sorted array", "palindrome", "remove in place", "3Sum") and it is the pattern that makes sorting first worth paying for.
The idea: keep two indices into the array and move them according to a rule, so that each step rules out part of the search for good.
Opposite ends on sorted input
Find two numbers in a sorted array that add up to a target. Start one pointer at each end.
- If the sum is too big, move the right pointer left (to a smaller number).
- If the sum is too small, move the left pointer right (to a bigger number).
- If it matches, you are done.
1 + 11 = 12, too big. Nothing pairs with 11: even the smallest number overshoots. Move R left.
Why is it safe to throw a number away? When nums[L] + nums[R] is too big, nums[R] plus any number at or right of L is at least as big, because the array is sorted. So nums[R] cannot be in any answer, and you lose nothing by dropping it.
nums[L] + nums[R] is smaller than the target. Why move L and not R?Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The same "squeeze from both ends" shape checks palindromes: compare s[left] and s[right], and move both inward while they match.
What does this print?
s = "racecar" left, right = 0, len(s) - 1 steps = 0 while left < right and s[left] == s[right]: left += 1 right -= 1 steps += 1 print(steps)
Valid Palindrome
A phrase is a palindrome if it reads the same forwards and backwards once you lowercase every letter and throw away everything that is not a letter or digit. Given a string s, return true if it is a palindrome.
"A man, a plan, a canal: Panama" → true ("amanaplanacanalpanama")
"race a car" → false ("raceacar")
" " → true (nothing left, which counts)Try to solve it without building a cleaned-up copy of the string.
Constraints
0 <= s.length <= 2 * 10^5scontains only printable ASCII characters.- Use O(1) extra space.
Same direction: read and write pointers
The second flavour moves both pointers the same way. A fast read pointer looks at every element; a slow write pointer marks where the next element you want to keep should go. This rearranges an array in place, with O(1) extra space.
Move all zeros to the end, keeping the other numbers in order:
r reads a 0. Zeros are not kept, so w stays put.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The same skeleton removes duplicates from a sorted array, removes all copies of a value, or partitions numbers around a pivot. Change the "is this a keeper?" test and you have a new solution.
Why sorting first can be worth it
Two pointers needs sorted input. Sorting costs O(n log n). That sounds like a loss next to the O(n) hash map approach, so when is it worth it?
- When you need O(1) extra space and are allowed to modify the input. A hash map costs O(n) memory.
- When the brute force is O(n²) or worse. For 3Sum (three numbers adding to 0), sorting costs O(n log n) and then fixing one number plus a two-pointer scan costs O(n²) total, down from O(n³).
- When sorted order makes skipping duplicates easy: equal values sit next to each other, so you can step over them.
What you lose: the original indices. If the question asks for positions in the original array, either use a hash map or sort (value, index) pairs.
Put the 3Sum approach in order.
- Tap the steps below in the right order.
Common mistakes
- Using
left <= rightin a pair search, so an element pairs with itself. Useleft < right. - Forgetting the input must be sorted. On unsorted input the "rule out" argument breaks and you will miss answers.
- Not skipping duplicates in 3Sum, producing the same triple several times.
- Moving both pointers when only one should move, skipping valid pairs.
- Returning sorted indices when the problem wanted original ones.
[8, 1, 6, 3] with target 9. What happens?3Sum
Given a list of integers nums, return every unique triplet [a, b, c] of values taken from three different positions where a + b + c == 0. Two triplets with the same values count as the same triplet, so do not repeat them. The order of the triplets, and of the values inside each one, does not matter.
nums = [-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]]
nums = [0, 1, 1] → []
nums = [0, 0, 0, 0] → [[0, 0, 0]]Constraints
3 <= nums.length <= 3000-10^5 <= nums[i] <= 10^5
- two pointers
- Two indices that move through an array by a rule so each step rules out part of the search.
- opposite ends
- One pointer at each end, squeezing inward. Used for pair sums on sorted input and palindromes.
- read/write pointers
- A fast pointer reads every element; a slow pointer marks where the next kept element goes. Rearranges in place.
- in place
- Changing the input array directly using O(1) extra memory instead of building a new one.
- 3Sum
- Find triples summing to zero: sort, fix one number, then two-pointer the rest. O(n²).