DEV Community

loading...
Cover image for Day 1: Two Sum

Day 1: Two Sum

mattryanmtl profile image Matt Ryan Updated on ・1 min read

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

Discussion (0)

Forem Open with the Forem app