Skip to content
intermediate

Two pointers on a sorted array

Complete the two-pointer scan that finds the pair summing to a target in one pass, without nested loops.

/**
 * Returns the indices of the two entries that sum to `target`, or null when
 * no such pair exists. `sorted` is ascending; each input is used at most once.
 */
export function pairWithSum(sorted: number[], target: number): [number, number] | null {
  let ____ = 0
  let _____ = sorted.______ - 1

  while (left < right) {
    const sum = sorted[left] + sorted[right]
    if (sum === target) return [left, right]
    if (sum < target) {
      left += 1
    } else {
      right -= 1
    }
  }

  return ____
}
0/4 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code