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 • Edited 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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay