Two Pointers (LeetCode #2)
Two pointers is the art of not restarting. A nested loop asks “for every i, try every j” — \(O(n^2)\). Instead you keep two indices and move them according to a rule that provably never skips the answer. This post explains the two layouts from scratch, then walks five problems in full: restated plainly, worked by hand on a concrete example, with the why before the code.
The technique
There are two layouts, and knowing which applies is the whole skill.
Converging pointers start at both ends and move toward each other. This works only when there is a reason to discard one side at each step — usually because the array is sorted, or because one boundary is provably limiting.
def converging(a):
l, r = 0, len(a) - 1
while l < r:
# look at a[l] and a[r], then move EXACTLY one side, with a reason
...
Same-direction pointers move left to right, one reading ahead and one writing behind — used to filter or partition in place.
def compact(a):
write = 0 # where the next kept element goes
for read in range(len(a)): # read scans ahead
if keep(a[read]):
a[write] = a[read]
write += 1
return write
Both are \(O(n)\) time and \(O(1)\) extra space. For a converging search the invariant is: the answer, if it exists, is always between l and r — every move must preserve that.
Valid Palindrome
The question. A string is a palindrome if it reads the same forwards and backwards. Given s, return True if it is one, ignoring everything that is not a letter or digit, and ignoring case.
Input: s = "A man, a plan, a canal: Panama"
Output: True
Just the letters: "amanaplanacanalpanama" — the same both ways.
Input: s = "race a car"
Output: False
The slow way. Build a cleaned copy (lowercase, letters/digits only), then compare it with its reverse. That works, but it uses \(O(n)\) extra memory for the copy and the reverse.
The idea. Compare the two ends and walk inward. Skip characters that are not alphanumeric, compare the next valid pair, and stop when the pointers meet. No copy needed.
Walk it through on "A man, a plan, a canal: Panama" (only the letters shown as a m a n a p l a n a c a n a l p a n a m a):
l |
r |
s[l] |
s[r] |
Match? |
|---|---|---|---|---|
a |
a |
a | a | yes → move both |
m |
m |
m | m | yes |
a |
a |
a | a | yes |
n |
n |
n | n | yes |
| … | … | … | … | all match |
If at any point the two valid characters differ, it is not a palindrome.
def is_palindrome(s):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum(): # skip punctuation/space on the left
l += 1
while l < r and not s[r].isalnum(): # skip on the right
r -= 1
if s[l].lower() != s[r].lower(): # compare the valid pair
return False
l += 1
r -= 1
return True
Why it works. Two strings are reverses of each other exactly when every mirrored pair of characters matches. We check all mirrored pairs once.
Complexity. \(O(n)\) time (each character is visited once), \(O(1)\) extra space.
Edge cases. Empty string → True. A single character → True. Strings with no letters/digits (e.g. "...") → True, because the cleaned string is empty.
Two Sum II (Input Array Is Sorted)
The question. Given a sorted array numbers (ascending) and a target, find the two numbers that add to target and return their 1-indexed positions.
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2] (numbers[0] + numbers[1] = 2 + 7 = 9, positions are 1-based)
Why this differs from Two Sum. Because the array is sorted, we can solve it with \(O(1)\) extra space instead of a hash map. Sorting gives us a direction to move.
The idea. Put one pointer at the smallest element (index 0) and one at the largest (last index). Look at their sum:
- If the sum equals the target, we are done.
- If the sum is too small, we need a bigger sum. The only way to get a bigger sum while keeping the small number is to move the left pointer right (to a larger value).
- If the sum is too large, move the right pointer left (to a smaller value).
We never need to consider the pairs we skipped, and the reason is the sorted order: the left element is the smallest available, so paired with the current right element it gives the smallest possible sum.
Walk it through on [2, 7, 11, 15], target 9:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
\foreach \v [count=\i from 0] in {2,7,11,15} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\node[font=\scriptsize\ttfamily, text=green!45!black] at (0,-0.55) {l};
\node[font=\scriptsize\ttfamily, text=orange!75!black] at (1.98,-0.55) {r};
\draw[->, thick, orange!80!black] (1.98,-0.38) -- (1.32,-0.35);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0.99,-0.9) {sum too big -> shrink r};
\end{tikzpicture}
l |
r |
a[l] |
a[r] |
Sum | Compared to 9 | Move |
|---|---|---|---|---|---|---|
| 0 | 3 | 2 | 15 | 17 | too big | r → 2 |
| 0 | 2 | 2 | 11 | 13 | too big | r → 1 |
| 0 | 1 | 2 | 7 | 9 | equal | return [1, 2] |
def two_sum_sorted(a, target):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target:
return [l + 1, r + 1] # 1-indexed
if s < target:
l += 1 # need a larger sum
else:
r -= 1 # need a smaller sum
return []
Why it works (the invariant). If a[l] + a[r] < target, then a[l] paired with any element at or below r is also too small, so a[l] can be discarded forever — moving l right is safe. Symmetrically for a[r]. So we never skip a valid pair.
Complexity. \(O(n)\) time, \(O(1)\) space — better memory than the hash map.
Edge cases. Exactly one solution exists. Positions are 1-based, so add 1 to each index. l and r must stay distinct (l < r).
3Sum
The question. Given an array nums, return all unique triplets [a, b, c] such that a + b + c = 0. The same triplet must not appear twice, even if the values repeat in the input.
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
The idea. Sort the array. Then pick each element nums[i] in turn as the first number of the triplet, and solve a Two Sum II on the rest of the array for the remaining -nums[i]. Sorting also makes duplicate-skipping easy.
Step by step. After sorting, nums = [-4, -1, -1, 0, 1, 2].
- Fix
i = 0, value-4. We need two numbers summing to4. Two Sum II finds none. Move on. - Fix
i = 1, value-1. Need two numbers summing to1. Left pointer at-1, right at2: sum1— found[-1, -1, 2]. Continue, skip the duplicate-1at index 2. - Fix
i = 3, value0. Need two numbers summing to0. Pointers find-1and1— found[-1, 0, 1]. - Fix remaining values; no more triplets.
Why skip duplicates? If nums[i] == nums[i-1], the same set of triplets would be produced again, so we skip. We also skip duplicate l values after a match.
def three_sum(nums):
nums.sort()
out = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate first element
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s == 0:
out.append([nums[i], nums[l], nums[r]])
l += 1
while l < r and nums[l] == nums[l - 1]:
l += 1 # skip duplicate second element
elif s < 0:
l += 1 # sum too small
else:
r -= 1 # sum too large
return out
Why it works. For each fixed first element, Two Sum II is correct by the invariant in Problem 2. Skipping duplicates removes repeated triplets, and sorting makes equal values adjacent so the skips are simple.
Complexity. Sorting is \(O(n \log n)\); the outer loop times the inner two-pointer scan is \(O(n^2)\). Extra space \(O(1)\) (ignoring the sort and output).
Edge cases. Fewer than three elements → no triplets. All zeros [0, 0, 0] → one triplet [0, 0, 0]. Large numbers are fine (compare sums, no multiplication). The output must contain unique triplets only.
Container With Most Water
The question. Each number height[i] is the height of a vertical line at position i. Choose two lines that, with the x-axis, form a container holding the most water. Water volume is width × min(height of the two lines).
Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Why the min? Water spills over the shorter wall, so the container is only as tall as the shorter line. Why the width? The lines are vertical at their indices; the container’s width is the gap between them.
The idea. Start with the widest possible container (the two ends). The width can only shrink as we move inward, so to have any chance of a bigger area, the height must increase — which means we should move the shorter side inward, because the shorter side is the one capping the current area.
Walk it through on [1, 8, 6, 2, 5, 4, 8, 3, 7]:
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\foreach \h [count=\i from 0] in {1,8,6,2,5,4,8,3,7} { \draw[thick, fill=blue!20] (\i*0.5,0) rectangle (\i*0.5+0.4,\h*0.18); }
\draw[very thick, green!55!black, <->] (0.2,0.32) -- (4.2,0.32);
\node[font=\scriptsize\ttfamily, text=green!45!black] at (2.2,0.55) {width};
\draw[thick, orange!80!black, <->] (4.35,0) -- (4.35,1.26);
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=west] at (4.4,0.63) {min height};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.2,-0.25) {move the shorter wall inward};
\end{tikzpicture}
| Step | l |
r |
Width | Min height | Area |
|---|---|---|---|---|---|
| start | 0 (1) | 8 (7) | 8 | min(1, 7) = 1 | 8 |
| move shorter (l) | 1 (8) | 8 (7) | 7 | min(8, 7) = 7 | 49 |
| move shorter ® | 1 (8) | 7 (3) | 6 | 3 | 18 |
| … | … | … | … | … | smaller |
The best is 49.
def max_area(heights):
l, r, best = 0, len(heights) - 1, 0
while l < r:
best = max(best, (r - l) * min(heights[l], heights[r]))
if heights[l] < heights[r]:
l += 1 # shorter wall caps the area -> move it
else:
r -= 1
return best
Why moving the shorter side is safe. Suppose the left wall is shorter. Keep the left wall fixed and move the right wall inward: the width shrinks and the height is capped by the left wall, so no container using the current left wall can beat what we already measured. So the current left wall is “used up” and we may discard it.
Complexity. \(O(n)\) time, \(O(1)\) space.
Edge cases. Fewer than two lines → area 0. Equal heights → move either side. All heights zero → 0.
Trapping Rain Water
The question. Given an elevation map where height[i] is the bar height, compute how much rain water is trapped between the bars.
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
The key formula. How much water sits on top of bar i? It is bounded by the tallest wall to its left and the tallest wall to its right — the water rises to the shorter of those two, then the bar itself takes up space:
\[ \text{water}[i] = \min(\text{leftMax}, \text{rightMax}) - \text{height}[i] \]
If that number is negative (the bar is taller than both walls), there is no water: clamp at 0. The companion note Trapping Rain Water derives this and walks four frames.
The two-pointer idea. Computing both maxima for every index from scratch is \(O(n^2)\). Instead, advance two pointers from the ends and keep the running maxima. At each step, the smaller of the two running maxima tells you the water height for that side, because the other side is guaranteed to have a wall at least as tall:
- If
leftMax <= rightMax, the water on the left pointer isleftMax - height[l], and we can movelright. - Otherwise, the water on the right pointer is
rightMax - height[r], and we moverleft.
Walk it through on [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]. The total is 6; the two-pointer pass adds it in one sweep without ever storing the arrays.
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\foreach \h [count=\i from 0] in {0,1,0,2,1,0,1,3,2,1,2,1} { \draw[thick, fill=blue!20] (\i*0.42,0) rectangle (\i*0.42+0.34,\h*0.22); }
\fill[cyan!30] (0.84,0) rectangle (1.18,0.22);
\fill[cyan!30] (1.68,0.22) rectangle (2.02,0.44);
\fill[cyan!30] (2.10,0) rectangle (2.44,0.44);
\fill[cyan!30] (2.52,0.22) rectangle (2.86,0.44);
\fill[cyan!30] (3.78,0.22) rectangle (4.12,0.44);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.5,-0.25) {water = min(leftMax, rightMax) - bar};
\end{tikzpicture}
def trap(height):
l, r = 0, len(height) - 1
left_max = right_max = water = 0
while l < r:
if height[l] < height[r]:
left_max = max(left_max, height[l])
water += left_max - height[l]
l += 1
else:
right_max = max(right_max, height[r])
water += right_max - height[r]
r -= 1
return water
Why it works. When height[l] < height[r], there is certainly a wall to the right at least as tall as height[l], so the water on the left is determined by leftMax alone. Each index is processed once.
Complexity. \(O(n)\) time, \(O(1)\) space. The precomputed-maxima version is also \(O(n)\) time but uses \(O(n)\) space; the two-pointer version is the space-optimal end of the ladder.
Edge cases. Fewer than three bars → 0. A monotonic slope traps no water. Zero-height bars trap fully (they are just gaps).
Pitfalls
- Using converging pointers on unsorted data for sums. The discard rule needs order; sort first or use a hash map.
- Advancing both pointers on a match in 3Sum. Advance one, then skip duplicates, or you can miss a valid triplet.
- Forgetting duplicate skips in 3Sum. Without them the output repeats triplets.
- Moving the taller wall in Container With Most Water. It can never increase the area.
- Off-by-one in the pointer update. Keep the loop condition (
l < r) consistent with the moves.
Why must the array be sorted for Two Sum II but not for the hash two-sum? Why move the shorter wall in Container With Most Water?
ASolution
The converging pointers discard a side based on the monotonicity of the sum, which requires order; the hash map instead remembers complements, so order does not matter. In Container With Most Water the area is bounded by the shorter wall, so moving the taller one only shrinks the width without raising the bound — moving the shorter one is the only move that can help.
Next: Stacks (LeetCode #3) — LIFO, monotonic stacks, and nested structure.