DEV Community

Cover image for Indices of the two numbers such that they add up to a specific target
chandra penugonda
chandra penugonda

Posted on • Updated on

Indices of the two numbers such that they add up to a specific target

Good morning! Here's your coding interview problem for today.

This problem was asked by Amazon.

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example
const twoSum = (nums, target) => {

};

console.log(twoSum([2, 7, 11, 15], 9))  // [0, 1]
// nums[0] + nums[1] = 2 + 7 = 9
Enter fullscreen mode Exit fullscreen mode

Solution

const twoSum = (nums, target) => {
  const obj = {};
  for (let i = 0; i < nums.length; i++) {
    const num = nums[i];
    const diff = target - num;
    if (obj[diff]) return [+obj[diff], i];
    obj[num] = i.toString();
  }
  return [-1, -1];
};
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Iterate through the nums array
  • Calculate the complement that would sum to target
  • Check if complement already exists in map
  • If so, return the indices
  • Otherwise, store num as key and index as value in map

Top comments (0)