Pair SumLoading saved progress…

Pair Sum

Given an array of numbers and a target sum, find two distinct positions in the array whose values add up to target. This is a classic warm-up — it's the first interview question many candidates see, and it's a good test of whether you can move from a brute-force O(n²) double loop to a one-pass O(n) lookup using a Set.

Implement pairSum(nums, target). Return the pair as a two-element array [a, b] in the order you encountered them while scanning left-to-right. If no such pair exists, return undefined.

Signature

function pairSum(nums, target) {
  // returns [a, b] where a + b === target and a, b come from distinct
  // positions in nums; returns undefined if no such pair exists.
}

Examples

pairSum([2, 7, 11, 15], 9);   // [2, 7]
pairSum([3, 2, 4], 6);        // [2, 4]
pairSum([1, 5, 3, 4], 10);    // undefined
pairSum([3, 3], 6);   // [3, 3] — two distinct positions, same value
pairSum([], 5);       // undefined
pairSum([5], 5);      // undefined — need two numbers

Notes

  • Distinct positions — the two numbers must come from different indices. pairSum([3], 6) is undefined, even though 3 + 3 === 6, because there's only one number.
  • Duplicate values are fine, as long as they sit at different indices. pairSum([3, 3], 6) returns [3, 3].
  • Order — return the pair in the order you meet them while scanning left to right. For [2, 7, 11, 15] and target 9, return [2, 7], not [7, 2].
  • First pair wins — if multiple pairs sum to target, return the first one you find during a single left-to-right scan.
  • No pair returns undefined, not null and not an empty array.
  • Don't mutate or sort the input array.
Loading editor…