.css-df1pn7{display:block;width:16rem;}     Code Challenge #3: Two Sum from LeetCode

Melvin Cayas

Published on Sep 19, 2021

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 + nums === 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 + nums === 9;

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-index j-index nums[i] nums[j] 0 1 2 7 0 2 2 11 0 3 2 15 1 2 7 11

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.