← Back to JavaScript, page 6

javascript-0115 · Medium mid

What is the two-pointer technique, and how do you use it for sorted pairs, in-place deduplication, and the container with most water?

Two pointers means walking an array with two indexes, either from both ends inwards or both from the front at different speeds, so a nested loop becomes a single O(n) pass. It works when moving a pointer has a predictable effect, such as on a sorted array. Typical uses are pair sums, removing duplicates in place, partitioning, and the container with most water.

Full answer

Many array problems look like they need two nested loops. If the data has an order, or the answer depends only on a relation between two positions, two indexes can replace the second loop.

Pattern 1, opposite ends: start left = 0 and right = n - 1 on a sorted array. For a target sum, compute sum = a[left] + a[right]. If it is too small, move left up to get a larger value. If it is too large, move right down. Each step discards at least one position, so the loop is O(n) and uses O(1) extra space. It only works because the array is sorted.

Pattern 2, same direction (slow and fast): write marks where the next kept value goes, and read scans ahead. For removing duplicates from a sorted array in place, copy a[read] to a[write] only when it differs from the last kept value. The first write items are the result, and the function returns the new length. Moving zeroes to the end and removing a value in place use the same shape.

Pattern 3, greedy contraction: for the container with most water, the area is min(height[left], height[right]) * (right - left). Moving the taller side can never help, because the width shrinks and the height is limited by the shorter side. So always move the pointer at the shorter line. This is O(n), compared with O(n squared) for all pairs.

Also useful: the fast and slow pointer idea for finding the middle of a linked list or detecting a cycle, and partitioning for the Dutch national flag problem.

When explaining, state the invariant: what is true about the part of the array already processed.

javascript
function pairWithSum(sorted, target) {
  let left = 0;
  let right = sorted.length - 1;
  while (left < right) {
    const sum = sorted[left] + sorted[right];
    if (sum === target) return [left, right];
    if (sum < target) left++;
    else right--;
  }
  return null;
}

function dedupeSortedInPlace(a) {
  if (a.length === 0) return 0;
  let write = 1;
  for (let read = 1; read < a.length; read++) {
    if (a[read] !== a[write - 1]) a[write++] = a[read];
  }
  return write;
}

function moveZeroesToEnd(a) {
  let write = 0;
  for (let read = 0; read < a.length; read++) {
    if (a[read] !== 0) {
      [a[write], a[read]] = [a[read], a[write]];
      write++;
    }
  }
  return a;
}

function maxArea(heights) {
  let left = 0;
  let right = heights.length - 1;
  let best = 0;
  while (left < right) {
    best = Math.max(best, Math.min(heights[left], heights[right]) * (right - left));
    if (heights[left] < heights[right]) left++;
    else right--;
  }
  return best;
}

console.log(pairWithSum([1, 2, 4, 7, 11, 15], 15), pairWithSum([1, 2, 3], 10));
const numbers = [1, 1, 2, 2, 2, 3, 5, 5];
const length = dedupeSortedInPlace(numbers);
console.log(length, numbers.slice(0, length), numbers);
console.log(moveZeroesToEnd([0, 1, 0, 3, 12]));
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]), maxArea([1, 1]));

Run with Node.js v24.22.1 as js-115.js; two runs gave identical output. Output: [ 2, 4 ] null 4 [ 1, 2, 3, 5 ] [ 1, 2, 3, 5, 2, 3, 5, 5 ] [ 1, 3, 12, 0, 0 ] 49 1

Key points

  • Replace a nested loop with two indexes that move in a predictable way, giving O(n).
  • Opposite ends on a sorted array: move left when the sum is too small, right when too large.
  • Same direction: write marks the kept prefix, read scans; used for in-place dedupe and removals.
  • Container with most water: always move the pointer at the shorter line.
  • State the invariant and note that sorting is often the precondition.

Common mistakes

  • Using the opposite-ends pattern on an unsorted array.
  • Forgetting that in-place deduplication leaves stale values after the returned length.
  • Moving the taller line in the container problem.
  • Using splice inside the loop, which turns an O(n) task into O(n squared).

Follow-ups

  • How would you solve three-sum with two pointers?
  • How do slow and fast pointers detect a cycle in a linked list?
  • How would you prove that moving the shorter line is safe in the container problem?

Tips

  • Name the pattern and say what makes it valid, usually sorted data.
  • Describe the invariant before the code.
  • Avoid splice in loops; write and read indexes are cheaper.