Interview OS
Back to Coding Prep

Coding

Two pointers

Two indices moving toward/with each other on sorted data.

Coding pattern

Overview

The two-pointer technique walks two indices through a sequence — usually sorted or naturally paired — to collapse an O(n²) search into O(n). It shines on pair-sum, palindrome, and partitioning problems where each comparison lets you safely discard one side.

How it works

Coding pattern
InputLeftRightOutputSorted arraysortedPointer Li=0Pointer Rj=n−1Converge
ClientServiceEdgeData

Step by step, with examples

  1. 1

    Sorted array

    • Best on sorted or naturally paired data.
  2. 2

    Pointer L

    • Start at the beginning of the range.
  3. 3

    Pointer R

    • Start at the end; move inward by comparison.
  4. 4

    Converge

    • Stop when the pointers meet or a match is found.
    • Example: Pair sum, palindrome

When to reach for it

  • Sorted arrays
  • Pair / triplet sums
  • Removing duplicates in place

Example problem

Pair sum in a sorted array.

Approach

  • Start at both ends
  • Move left up if sum too small, right down if too large

Solution

function pairSum(nums, target) {
  let i = 0, j = nums.length - 1;
  while (i < j) {
    const s = nums[i] + nums[j];
    if (s === target) return [i, j];
    s < target ? i++ : j--;
  }
  return [-1, -1];
}

Complexity

Time O(n), Space O(1).

Common pitfalls

  • Forgetting the array must be sorted
  • Skipping duplicates incorrectly

Where this content comes from

For full transparency, this content is curated and verified from these sources:

Curated company-tagged problem banksRecurring interview pattern librariesOppZen-authored drills & solutions