Dev HelpersOpen library
← Back

Find two-sum indices

Find two-sum indices. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const twoSum = (xs, target) => {
  const seen = new Map();
  for (let i = 0; i < xs.length; i++) {
    if (seen.has(target - xs[i])) return [seen.get(target - xs[i]), i];
    seen.set(xs[i], i);
  }
  return [];
};
console.log(twoSum([2, 7, 11], 9));

Sample output

[ 0, 1 ]