Back

Two Pointers

Two Pointers uses two variables moving through data, usually one from each end. It replaces nested loops with a single loop, making your code much faster. Use it on sorted arrays when looking for pairs or comparing from both sides.

// Check if array has two numbers that sum to target
function twoSum(nums: number[], target: number): boolean {
  let left = 0
  let right = nums.length - 1

  while (left < right) {
    const sum = nums[left] + nums[right]
    if (sum === target) return true
    if (sum < target) left++   // need bigger number
    if (sum > target) right--  // need smaller number
  }

  return false
}

Roadmap