Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 15 minutesNeeds: arraysTime O(n)Space O(1)

2 · Watch

Two Pointers in 60 seconds

Nine walls stand in a row, and you must pick the pair that holds the most water. Trying every pair means measuring 36 containers.

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.
  1. Easy01

    Valid Palindrome

    LeetCode 125 · Blind 75 · NeetCode 150

    Warm-up: ends walk inward, skipping anything that isn’t a letter or digit.

  2. Medium02

    3Sum

    LeetCode 15 · Blind 75 · NeetCode 150

    Sort first, then run two pointers from every start.

  3. Medium03

    Container With Most Water

    LeetCode 11 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

UP NEXT · LESSON 3 OF 20Sliding WindowA range that grows and shrinks as it scans.