0

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 ]

  • 2
    Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Sep 30 '22 at 17:24
  • why do you use a `*` in `console.log(ds) *` ? I think you need to use a `'use strict';" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode... – Mister Jojo Sep 30 '22 at 17:30

1 Answers1

1

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]]

harryh
  • 346
  • 2
  • 9