-2

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

Carolyn Cordeiro
  • 1,525
  • 3
  • 11
  • 26
  • instead of pushing the value at array[i] in nums, push i – about14sheep Dec 17 '21 at 23:52
  • 4
    Please don't ever iterate an array with `for(let i in array){...}`. `for/in` is for iterating properties of an object, not elements of an array. For details as to why, see here: https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements/22754453#22754453. Use `for/of` to iterate items of an array. – jfriend00 Dec 17 '21 at 23:55

1 Answers1

1

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.

tromgy
  • 4,937
  • 3
  • 17
  • 18