DEV Community

codingpineapple
codingpineapple

Posted on

LeetCode 1. Two Sum (javascript solution)

Description:

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

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

You can return the answer in any order.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var twoSum = function(nums, target) {
    const store = {}
    for(let i = 0; i < nums.length; i++){
      let cur = nums[i]
      let diff = target - cur
      // Return answer if the current number was a diff from a previous number
      if(store[cur]!==undefined) return [store[cur], i]
      // Set diff to current index in store
      else store[diff] = i
    }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)