Home > Blockchain >  Why the array returned by the combinationSum function is empty (Javascript)?
Why the array returned by the combinationSum function is empty (Javascript)?

Time:10-01

The resultArr returned by the combinationSum function is empty. When I console log the ds array, it prints the correct answer, but the final output array is [[],[]].

var combinationSum = function(candidates, target) {
    const resultArr = []
    function combinationSumHelper(idx, candidates, ds, target){
        if(idx === candidates.length){ // base case
            if(target === 0){
                console.log(ds) *// This line outputs right ans but resultArr returned by combinationSum function is empty*
                resultArr.push(ds)
            }
            return
        }
        if(candidates[idx] <= target){
            ds.push(candidates[idx])
            combinationSumHelper(idx, candidates, ds, target - candidates[idx])
            ds.pop()
        }
        combinationSumHelper(idx 1, candidates, ds, target)
    }
    combinationSumHelper(0, candidates, [], target)
    return resultArr
};

console.log(combinationSum([2,3,6,7], 7))

OUTPUT: [ [], [] ]

EXPECTED OUTPUT: [[2,2,3],[7]]

STDOUT: [ 2, 2, 3 ] [ 7 ]

CodePudding user response:

This will give you the output you are looking for:

var combinationSum = function(candidates, target) {
    const resultArr = []
    function combinationSumHelper(idx, candidates, ds, target){
        if(idx === candidates.length){ // base case
            if(target === 0){
                console.log(ds) *// This line outputs right ans but resultArr returned by combinationSum function is empty*
                resultArr.push([...ds])
            }
            return
        }
        if(candidates[idx] <= target){
            ds.push(candidates[idx])
            combinationSumHelper(idx, candidates, ds, target - candidates[idx])
            ds.pop()
        }
        combinationSumHelper(idx 1, candidates, ds, target)
    }
    combinationSumHelper(0, candidates, [], target)
    return resultArr
};

console.log(combinationSum([2,3,6,7], 7))

The problem you are facing is the below if clause with ds.push and ds.pop is mutating your array and the final output.

By changing your code to resultArr.push([...ds]), you can make a copy of your array. This will ensure it will not get mutated further on.

When I run this code the output I get is: [[2, 2, 3], [7]]

  • Related