Drill

ProblemsJavaScript › warmup

Find the two that add up

mediumwarmupJavaScript

A reconciliation tool looks for the two entries that together explain a difference.

pairSummingTo(values: list<int>, target: int) → list<int>

Solve it in the editor →

Where you start

function pairSummingTo(values, target) {
  
}

Worked examples

CallResult
pairSummingTo([2,7,11,15], 9)[0,1]
pairSummingTo([3,2,4], 6)[1,2]
pairSummingTo([3,3], 6)[0,1]
pairSummingTo([1,2], 99)[]

Hint

Walk once, and for each value ask whether the number that would complete it has already gone by.

Reference solution in JavaScript
function pairSummingTo(values, target) {
  const seen = new Map();
  for (let j = 0; j < values.length; j++) {
    const need = target - values[j];
    if (seen.has(need)) return [seen.get(need), j];
    if (!seen.has(values[j])) seen.set(values[j], j);
  }
  return [];
}

The same problem in another language

More warmup problems in JavaScript