Two Pointers
Two people start at opposite ends of a hallway and walk toward each other. Each step rules out a whole row of options they will never need to check. Two pointers prune a search the same way: every move discards what cannot win.
2 · Watch
Two Pointers in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Container With Most Water
or try
2–10 wall heights from 0 to 9, separated by spaces.Start with the widest container: the first and last walls.Step 1 of 18. Starting out. 9 walls. Widest container first: wall 0 and wall 8.
Step 1 of 18
solution.ts
function maxArea(height: number[]): number {
let left = 0, right = height.length - 1;
let best = 0;
while (left < right) {
const h = Math.min(height[left], height[right]);
best = Math.max(best, h * (right - left));
if (height[left] < height[right]) left++;
else right--;
}
return best;
}
▶ marks the line running now
4 · Your turn
0 of 3 problems solved
Start from this
// Start at both ends of the sorted array.
let l = 0, r = nums.length - 1;
while (l < r) {
if (isAnswer(l, r)) return [l, r];
// Each step rules out one end for good.
if (needBigger(l, r)) l++;
else r--;
}Easy ways to go wrong
- Forgetting to sort first when the logic depends on order.
- Using l <= r when a pair needs two different elements.
- Not skipping duplicates in problems that ask for unique answers.
- Easy01
Valid Palindrome
Warm-up: ends walk inward, skipping anything that isn’t a letter or digit.
Compare the outside pair, then work inward.
- Time
- O(n)
- Space
- O(1)
- Medium02
3Sum
Sort first, then run two pointers from every start.
Sort, fix one number, then close in on the other two from both ends.
- Time
- O(n²)
- Space
- O(1)
- Medium03
Container With Most Water
The one you just watched. Write it from memory.
Start with the widest pair. Only moving the shorter line can ever help.
- Time
- O(n)
- Space
- O(1)
Also works with Greedy.