Javascript Solution to Two Sum Problem from LeetCode
Time Complexity: O(n) + O(1) = O(n)
Run the code here: https://repl.it/@VinitKhandelwal/1-Two-Sum
Problem:
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].
Map the numbers to their indices as we iterate, so that we can look them back up in O(1) time complexity.
const func = function(nums, target) {
const indicies = {} // objects are hash table in javascript
for ( i = 0; i < nums.length; i++ ) {
const num = nums[i];
const val = indicies[num];
if (val == null) {
indicies[target - num] = num;
} else {
return [val, num];
}
}
}
func([1,3,2,6,5], 9);
Run the code here: https://repl.it/@VinitKhandelwal/1-Two-Sum
Comments
Post a Comment