Two Sum Part ll
For this blog, I’ll be going over how to solve this specific Two Sum problem. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:
In other words, the prompt is asking us to create a function that takes in an array of integers (numbers
) and a target
. If the target
is 9, then the function should be able to return the indices of the two integers in numbers
that add up to the target
(9). We also need to understand that there can only be one solution. Also, if we take a look at example 1 from the picture above, we can see how the output is [1,2]
instead of [0,1]
. That’s because it’s being added by 1!
First, I’m going to create various variables that are going to be essential in solving this problem. The first variable that I’ll be creating is left
, left
will be representing the direction in which that iteration or loop goes starting from left to right. The next variable is right
which represents the direction of the iteration from right to left. The last variable will be representing 0 because we’re going to change its value as the iteration is happening. Here’s what the code should look like right now:
Next, I’m going to create a while
loop. The while
loop will stop running when left
becomes greater than right
. Here’s what the code looks like so far:
Now that the while
loop is created, we can change the value of theSum
and write a couple of conditionals that would return what we want! theSum
is now going to be equal to the current number being iterated on the left (numbers[left]
) or the current number starting from the right (numbers[right]
). I’m only using theSum
because I would like my code to be cleaner and more readable! Here’s what the code should look like so far:
The next few steps are going to work closely together in order to return the output that we need. First we’re going to create an if
statement that returns the indices plus 1 if theSum
is equal to the target
. Also if theSum
is greater than the target
, then we need to continue the loop. Finally, the last part is to continue the iteration to the left if theSum
is not equal to the target
. Here’s what the full solution should look like:
Here are the results for the examples on lines 17–19:
Here’s the solution on LeetCode:
I hope this blog was helpful in any way! For more info on while
loops checkout the resource section below!