Two Sum solved in javascript
Somnath.geek
Posted on December 29, 2019
Two Sum : Javascript
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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Code:
var twoSum = function(nums, target) {
//hash table
var hash = {};
for(let i=0; i<=nums.length; i++){
//current number
var currentNumber = nums[i];
//difference in the target and current number
var requiredNumber = target - currentNumber;
// find the difference number from hashTable
const index2 = hash[requiredNumber];
// if number found, return index
// it will return undefined if not found
if(index2 != undefined) {
return [index2, i]
} else {
// if not number found, we add the number into the hashTable
hash[currentNumber] = i;
}
}
};
In detail:
- Declare a empty hash table
- Loop through the array
- Store the current number in a variable
- Find the difference between the the target number and the current number
- Search for the difference number from the hash table
- If number found, return the index of the first number and the search number
- If not found, add the number into the hash table and continues for loop checking.
Conclusion:
Hashmap is the optimal solution as the average search time complexity is O(1)
Runtime | Memory |
---|---|
84 ms | 35.5 MB |
💖 💪 🙅 🚩
Somnath.geek
Posted on December 29, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.