Solving Leetcode Two Sum in JS

JakePino
3 min readJan 2, 2021

Solving algorithms is something all junior developers need to get familiar with. The website Leetcode.com is one of the most popular for honing your algorithm skills, and Two Sum is one of their best known. All junior devs should give this a crack, so let's take a look at this problem now and solve it.

The Prompt

If, for example, nums = [2, 7, 20, 24] and target = 9, then our return would be [0, 1] since nums[0] = 2 and nums[1] = 7, and 2+7 = 9.

The Solution

Since our problem will require checking the sum of two elements in the nums array and comparing it to the target integer, we know we will need a loop. We will use a basic for loop for this. But before that, let’s make an Object. We will use this object to store not the sum of two elements in the array, but rather the difference of the target integer and each element in the nums array. Inside the for loop, we will store each diff variable inside of our object as a key. The value of each key will be the value of i. But before we do that, we will set up a conditional. If the key of our diff exists in our object, we will return both the object and the value of i. If it does not exist, then we will create a new key, set as the diff with a value of i. We end up having something that looks like this:

So let’s examine this using our example to check it. If nums = [2, 7, 20, 24] and our target is 9, then when i = 0 our diff will be 9–2 = 7. Our dict doesn't yet have any keys, since it’s our first iteration, so we’ll skip the if statement and we’ll make a key, and our dict will now be {2:0}. During our second loop, i = 1, and nums[1] = 7. Our diff is 9–7=2, and since 2 was our first element which we created a key for, our if conditional gets triggered and we return the value of our key and also our current i. This yields 0, our stored value of dict[diff], and our current i of 1. Thus our answer is [0, 1].

Happy hunting and hit those algos!

--

--

JakePino

California native, living in NYC., Software Engineer.