Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created October 26, 2024 18:21
Show Gist options
  • Save sAVItar02/a2bd53e402b02afb7b517ac4fb68226c to your computer and use it in GitHub Desktop.
Save sAVItar02/a2bd53e402b02afb7b517ac4fb68226c to your computer and use it in GitHub Desktop.
Two Sum
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let map = new Map();
for(let i=0; i<nums.length; i++) {
let numToFind = target - nums[i];
if(map.has(numToFind)) return [map.get(numToFind), i];
else map.set(nums[i], i);
}
return null
};
// Store the elements in a hashmap
// Start traversing the array and find (target - element at current iteration)
// If the map has the item needed, then return the current iteration value and the value found
// If not then add the value to the map and move on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment