Code Challenge #3: Two Sum from LeetCode

Code Challenge #3: Two Sum from LeetCode

Welcome back!

Today's challenge is the Two Sum problem from LeetCode. I did this with JavaScript, but I may redo this in the future since I'm currently learning Java!

The Challenge

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:

  • Input: nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1]
  • Output: Because nums[0] + nums[1] === 9, we return [0, 1].

Example 2:

  • Input: nums = [3, 2, 4], target = 6
  • Output: [1, 2]

Example 3:

  • Input: nums = [3, 3], target = 6
  • Output: [0, 1]
// JavaScript example
const nums = [2, 7, 11, 15];
const target = 9;

const output = twoSum(nums, target);
console.log(output) // [0, 1] because nums[0] + nums[1] === 9;

STOP READING if you want to try this on your own!

My Solution

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */

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

I decided to use two for loops because it could iterate over two elements at once. The second loop has the index of j = i + 1 to start at the next element.

It can be hard to visualize, but the first loop will execute and won't go to the next index, i = 1, until the second loop iterates through the array.

For example, this is how the operation would look for the first few indexes if nums was an array of [2, 7, 11, 15]:

i-indexj-indexnums[i]nums[j]
0127
02211
03215
12711

And so on...

Then the if-statement in the second for loop checks if the sum of nums[i] and nums[j] equals the target.

if (nums[i] + nums[j] === target) {
    return [i, j];
}
// Using === to compare both the value and the type

It returns the indexes as [i, j] if it finds a match, ending the loop.

It's Your Turn

Did you do this challenge differently? I'm sure my code isn't the most optimal way of doing this. Let me know in the comments!

Feel free to check out the CodePen!

 
Share this