Skip to content
Advertisement

Node JS displaying value at index instead of indices

Written this 2sums code to get efficent O(N) Time complexity algorithm for below problem

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

unfortunately saw value at array nums got displayed in the output ,whereas the need is to get the indices to be displayed in output

What change needs to be done below

            let hashTwoSum = (array, sum) => {
                let numsObj = {}
                let nums = []
               
                for(let i in array){
                    let addend = sum - array[i]
                   
                    if (addend in numsObj){

                        nums.push([addend, array[i]])

                    }
                    numsObj[array[i]] = i

                    
                }
                return nums
                
            }

            let array = [2,7,11,15]
            console.log(hashTwoSum(array,9))
            
            

Your help is appreciated

Regards,

Carolyn

Advertisement

Answer

As @jriend00 said, do not use for(... in ...) loop for iterating arrays. But in your case, where you need indices, you need to use the good old for loop: for(let i = 0; i < array.length; i++). And when you save results, you need to push both indices: nums.push([numsObj[addend], i]).

Here’s a complete example:

let hashTwoSum = (array, sum) => {
    let numsObj = {}
    let nums = []

    for(let i = 0; i < array.length; i++){
        let addend = sum - array[i]

        if (addend in numsObj){
            nums.push([numsObj[addend], i])
        }
        numsObj[array[i]] = i
    }
    return nums
}

let array = [2,7,11,15,6]
console.log(hashTwoSum(array,17))

This will output:

[ [ 0, 3 ], [ 2, 4 ] ]

because 2 + 15 and 11 + 6 are both equal 17.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement