Skip to content

Instantly share code, notes, and snippets.

@tombaranowicz
Created August 7, 2019 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombaranowicz/be9ef93be5a42d0b25358bdad52b6d2a to your computer and use it in GitHub Desktop.
Save tombaranowicz/be9ef93be5a42d0b25358bdad52b6d2a to your computer and use it in GitHub Desktop.
2 ways of solving "Two Sum" coding interview problem in JavaScript.
// var twoSum = function(nums, target) {
// for(index = 0; index < nums.length - 1; index++) {
// for(i = index+1; i< nums.length; i++) {
// let sum = nums[index] + nums[i];
// if (sum == target) {
// return [index, i];
// }
// }
// }
// };
var twoSum = function(nums, target) {
let d = {};
for(i = 0; i< nums.length; i++) {
if (d[target-nums[i]] >= 0) {
return [d[target-nums[i]], i];
}
d[nums[i]] = i;
}
};
const nums = [2, 7, 11, 15];
const target = 9;
console.log(twoSum(nums, target));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment