Two Sum Problem - Javascript Solution
/**
- Topic: Interview questions
- Problem: Two Sum Problem
- Description: Given an array on integer array and a target value,
- find the pair of elements which when added is equal to target value.
- Eg. array = [1,4,2,5,6,8] target = 9, here output will be [1,3] as 4 + 5 = 9
- Author: Vishal Das(Moonvil)
**/
var twoSum = function(nums, target) {
const hash = {};
for(let i = 0; i < nums.length; i++){
if(hash[nums[i]] > -1) return [hash[nums[i]],i]
else{
const diff = target - nums[i];
hash[diff] = i;
}
}
return [-1,-1]
};
console.log(twoSum([2,7,11,15],9))