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

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;
}
}

--

--

--

Always learning.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

JS Demystified 04 — Execution Context

Building Enterprise Web Applications with Monorepo Architecture

Solving Coding Challenges with JavaScript Functions on Autocode

Experiment with p5.js and Vue

🚀 Huobi is sending one winner to space! 🚀

Property ‘_write’ in type ‘ClientDuplexStreamImpl<RequestType, ResponseType>’ is not assignable to…

Strongly Typed Mongoose Models with Typegoose & TypeScript

How to use promise() in Javascript / VueJS

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
Saul Feliz

Saul Feliz

Always learning.

More from Medium

Switch overview in JavaScript

JavaScript Project Reflections

Data Structures : Comparisons Between Different Algorithms

Why is use function is the benefit? what is the benefit of it?