Skip to article content
FrontendXLesson 07 / 24

Two pointers

Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.

intermediate · about 30 minutes · 3 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Use converging pointers to solve sorted pair problems in O(n).
  • Decide which pointer to move from the comparison result.
  • Recognize when two pointers replace a nested loop.

Overview

#

Replace the inner loop

A brute-force pair search is O(n^2). If the array is sorted, two pointers reduce it to O(n) by using order to discard many candidates at once.

Converging pointers

Find two values that sum to a target in a sorted array:

snippet.txt
function twoSumSorted(values, target) {
  let left = 0;
  let right = values.length - 1;
  while (left < right) {
    const sum = values[left] + values[right];
    if (sum === target) return [left, right];
    if (sum < target) left++;
    else right--;
  }
  return [-1, -1];
}

Why moving one pointer is safe

If the sum is too small, the current left paired with any element to the left of right would be even smaller, so left cannot be part of a valid pair with the current range. Advancing left is safe. The mirror argument holds when the sum is too large. Each step removes at least one candidate, so the loop is O(n).

Same-direction pointers

Two pointers can also move the same way, for example to remove duplicates from a sorted array or to partition by a predicate. One pointer scans, the other marks where the next kept element belongs.

When two pointers do not apply

If the data is not sorted and cannot be sorted cheaply, or if the answer depends on values in a way order does not reveal, two pointers will not help. In those cases a hash map is often the better tool.

Practice next

  • Extend the sorted two-sum to three-sum by fixing one element and using two pointers on the rest.
  • Maximise the area between two lines using converging pointers.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    For values [1, 2, 4, 7, 11] and target 9, which index pair does the converging two-pointer search return?

    starter.javascript
    let left = 0, right = 4;
    // compare values[left] + values[right] with 9

    Reveal the reference answer
    reference.javascript
    1 + 11 = 12 > 9, so right becomes 3. 1 + 7 = 8 < 9, so left becomes 1. 2 + 7 = 9, found. It returns [1, 3].

    Authored expected output: [1, 3]

    The trace shows the range shrinking until the pair is found.

  2. Exercise 2Explain

    Explain why advancing left is safe when values[left] + values[right] is less than the target in a sorted array.

    Reveal the reference answer
    reference.text
    If the sum with the largest remaining element is already too small, then pairing values[left] with any smaller element (everything left of right) is even smaller. So values[left] cannot be part of any valid pair within the current range, and it is safe to discard it.

    Authored expected output: The largest partner already gives too small a sum, so left cannot pair with anything in range.

    This discard argument is what turns O(n^2) into O(n).

  3. Exercise 3Implement

    Implement removeDuplicatesSorted(values) that returns the count of unique values, keeping them at the front of the array in place.

    starter.javascript
    function removeDuplicatesSorted(values) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function removeDuplicatesSorted(values) {
      if (values.length === 0) return 0;
      let write = 1;
      for (let read = 1; read < values.length; read++) {
        if (values[read] !== values[write - 1]) {
          values[write] = values[read];
          write++;
        }
      }
      return write;
    }

    Authored expected output: 3 for input [1, 1, 2, 3, 3]

    The read pointer scans and the write pointer marks where the next distinct value belongs, giving O(n) time and O(1) space.

Common misconceptions

#
  • Two pointers always means one at each end. Same-direction pointers are also two pointers.
  • Two pointers work on unsorted data without sorting. The discard argument needs order.
  • Moving both pointers on every step is fine. Move only the pointer that the comparison justifies.

Follow-up practice

#
  • dsa-from-zero-sliding-window

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.