AndrewNeedsHelp
AndrewNeedsHelp

Reputation: 415

Two Sum Algorithm - Using Find Index - Javascript Algorithm

Question

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.

But, I specifically want to use the findIndex() to solve this. The problem is we need two indices to add together! Not just one.

function twoSum(arr, target){

let relevantArr = [];

let newArr = arr.slice(0,);

function test(){

return newArr.findIndex(added);

}

function added (a, b) {
  a + b == target;

}


return relevantArr
}



console.log(twoSum([2, 7, 11, 15], 9))

Help appreciated, if you know a way to make this work!

Upvotes: 1

Views: 947

Answers (2)

trincot
trincot

Reputation: 351084

Indeed, if you want to use findIndex, then its return value can never be enough, as it is only one index. You could use a "side effect" and use another variable to store the second index. For finding the second index, don't use findIndex again, as that is overkill. Use indexOf, and make sure it only scans the part of the array that comes after the first index (using the second argument of indexOf):

function twoSum(arr, target) {
    let j = -1; // Needs to be accessible by the following function:

    function added(val, i) {
        // modify the variable outside of this function scope:
        j = arr.indexOf(target - val, i + 1);
        return j >= 0; // true if success
    }

    // findIndex will modify j, which we add to the pair
    return [arr.findIndex(added), j]; // will be [-1, -1] when not found
}
console.log(twoSum([2, 7, 11, 15], 9)); // found
console.log(twoSum([2, 7, 11, 15], 100)); // not found

The added function is now a "dirty" function, because it alters a variable in the outer scope. But this is closest to what you were trying to do.

A plain for loop would be more called for (together with the indexOf). And for large arrays, you would benefit from first creating a map, so you don't need a linear look up within that loop, but a constant one.

Upvotes: 1

Joffrey Schmitz
Joffrey Schmitz

Reputation: 2438

You can loop on the array items and try to find its complement to get the target. If the complement is not found, findIndex returns -1 and you check the next one.

function twoSum(arr, target){
    for(let i = 0, len = arr.length ; i < len ; ++i)
    {
        // try to find an item so that its sum with arr[i] is equal to the target
        let j = arr.findIndex(item => item + arr[i] == target); 
        if(j != -1)
        {
            // we found the element, we can return the answer
            return [i, j];
        }
    }
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0,1]
console.log(twoSum([2, 7, 11, 15], 18)); // [1,2]

Upvotes: 1

Related Questions