Last active
May 11, 2020 12:34
-
-
Save deemaxx/be0d6280708532c9890757e7c8d455fa to your computer and use it in GitHub Desktop.
Find 2 numbers in an array input that up add to a target number and return their indices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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. | |
* | |
* @param {Array<number>} nums | |
* @param {number} target | |
* @return {Array<number>} | |
*/ | |
const nums: Array<number> = [3, 5, 8, 15, 22, 78] | |
const target: number = 30 | |
const twoSum = function(nums: Array<number>, target: number): Array<number> | undefined { | |
// look up set | |
// loop over the input array | |
// Evaluate if the lookup hash has a property equating to current index's value | |
// if true, return an array containing this propertie's index value along with current loop index. | |
// else add the current index value to lookup hash table and assign its index | |
let lookup: object = {} | |
for (let i = 0; i < nums.length; i++) { | |
// lookup.hasOwnProperty(lookup[30-3]) --- false | |
// lookup.hasOwnProperty(lookup[30-5]) --- false | |
// lookup.hasOwnProperty(lookup[30-8]) --- false | |
// lookup.hasOwnProperty(lookup[30-15]) --- false | |
// lookup.hasOwnProperty(lookup[30-22]) --- true | |
if (lookup.hasOwnProperty([target - nums[i]])) { | |
return [lookup[target - nums[i]], i] // [2, 4] | |
} | |
// lookup[3] = 0 // { 3: 0 } | |
// lookup[5] = 1 // { 3: 0, 5: 1 } | |
// lookup[8] = 2 // { 3: 0, 5: 1, 8: 2 } | |
// lookup[15] = 3 // { 3: 0, 5: 1, 8: 2, 15: 3 } | |
lookup[nums[i]] = i | |
} | |
}; | |
twoSum(nums, target) // result: [2, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment