DEV Community

Cover image for Day 1: Two Sum
Matt Ryan
Matt Ryan

Posted on • Edited on

Day 1: Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Javascript:

var dayOne = function (nums, target) {
  var sum = {}
  for (var i = 0; i < nums.length; i++) {
    if (!Object.prototype.hasOwnProperty.call(sum, (target - nums[i]))) {
      sum[nums[i]] = i
    } else {
      return [i, sum[target - nums[i]]]
    }
  }
}

console.log(dayOne([2, 7, 11, 15], 9))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)