twoNumbers()

Joseph K Abe
2 min readOct 30, 2021

Two numbers is a fun problem where you are tasked to create a function that takes 2 arguments; an array of numbers and a target. Within the array of numbers there are 2 numbers of which their sum will equal the target. We are then asked to return the indexes of the 2 numbers. The function will look like this…

function twoNumbers(nums, target){}

My solution to this problem was a pretty simple one. If we are trying to find 2 numbers that add up to equal our target we must be able to subtract the numbers of the array we are given to find the number…

for (let i = 0; i - nums.length; i++){
let num = nums[i]
let numIndex = nums.indexOf(num)
}

The first step is to make a for loop to iterate the array. We are making a let named num that is each number of the array, and a let called numIndex that is the index of each of those numbers.

Now we can start subtracting these numbers from our target and check if the the difference is present in or array of numbers!

let otherNum = target - num
let otherNumIndex = nums.lastIndexOf(otherNum)
if(nums.includes(otherNum) && (numIndex != otherNumIndex)){
return [numIndex, otherNumIndex]

If the difference of target — num is present in the array of numbers then that will be our otherNumbers. All we have to do is use lastIndexOf() to find the index of the otherNumber. Here is the final solution

function twoNumbers(nums, target){
for (let i = 0; i - nums.length; i++){

let num = nums[i]
let numIndex = nums.indexOf(num)
let otherNum = target - num
let otherNumIndex = nums.lastIndexOf(otherNum)
if(nums.includes(otherNum) && (numIndex != otherNumIndex)){
return [numIndex, otherNumIndex]
}
}

This is a pretty simple solution to the twoNumbers problem and I’m sure there are much more efficient ways to solve it. Using methods like array.includes() is definitely not the quickest way to search through an array, but that being said sometimes its good to keep it simple!

--

--