Explaining Leetcode’s Two Sum Problem (JavaScript)

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
}

Making it more efficient with extra caching and a little logic

As mentioned before, every algorithm has a trade off. A more efficient solution in terms of time, has the tradeoff that,

function twoSum(nums, target) {let numObj = {};
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i];
if (numObj[complement] !== undefined) {
return [numObj[complement], i];
}
numObj[nums[i]] = i;
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store