LeetCode 1. Two Sum (javascript solution)

cod3pineapple

codingpineapple

Posted on April 17, 2021

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
πŸ’– πŸ’ͺ πŸ™… 🚩
cod3pineapple
codingpineapple

Posted on April 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related