DEV Community

Cover image for LeetCode's Two Sum challenge
12 Gage
12 Gage

Posted on

LeetCode's Two Sum challenge

Welcome to the Two Sum code challenge.

Instructions -

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.

Let’s break down these instructions really quick, there’s something important here.

The first part is self explanatory, however there is a catch in the second line.

“You may assume that each input would have exactly one solution, and you may NOT use the same element twice.”

There could be multiple items that, when added, would equivalate to the target.

We only have to worry about the first one that matches. However, the rules state that you may not reference the same item’s index more than once when comparing the item’s sum to the target value.

Putting It In Simple Terms -

If two items from an array, when added together, have same value as the target value- return the index of those items.

Meaning that we want to keep reference of the items index when doing the comparison.

It’s pretty simple, really. So without further ado, let’s get to the solution.

Implementation -

The first issue I ran into with this challenge is that I wanted to make use of the JS method indexOf() to get the index of my items. The problem is that indexOf() only returns the index of the FIRST index that matches that value- meaning that it wouldn’t pass the test because it breaks the “same element twice” rule.

So how can we get around this?

Let’s get to coding.

We know that we have to loop through this array at least once to see all of its contents.

We also know that we’ll want to make a second loop to compare one item to the rest of the entire array.

I decided to go with a traditional for loop so that I can reference my index directly from the variables that I created when initiating the for loop. (i and second)

NOTICE- My second variable is not used the same way as my i variable. It’s actually set to i + 1 so that I can assure that I never compare the same item to itself.

Solving the ‘same element twice’ issue.

Now that we have that out of the way, let’s look at the condition.

if (nums[i] + nums[second] == target)

So in this example if 2 + 7 == 9 (which it does)

{ return the counter variables in the form of an array }

Which in this case it would look like [i, second]

And that’s pretty much it! I felt like the same element rule was quite a curve ball, and if you found a different way of solving it comment below!

I’d love to look at another solution and compare it to the way that I initially thought about it.

I hope this post was helpful, thanks for reading!

Top comments (0)