Search code examples
javascriptpushdestructuring

why when I push the track to array, all the elements in array changed


I try to solve leetcode 46. Permutations in JS, but the code below gets wrong result, but when using res.push([...track]) instead of res.push(track) will be correct. I'm to confused about this, in my mind these two are the same. Thank you!

var permute = function(nums) {
    const res = []
    backtrack(res, [], nums)
    
    return res
};

var backtrack = function(res, track, nums) {
    if (track.length == nums.length) {
        console.log('track: ', track)
        console.log('res: ', res)
        console.log()

        res.push(track)
        //res.push([...track])
        return 

    }
    
    for (let i = 0; i < nums.length; i++) {
        if (track.includes(nums[i])) continue      
        track.push(nums[i])
        backtrack(res, track, nums)
        track.pop()
    }
}

const res = permute([1,2,3])
console.log(res)

Solution

  • Because res.push(track) this keeps the reference of track array inside res array. And when you change track afterwards res array also changes. So you need to create a new array with the items from track by doing [...track]. For example,

    let res = [];
    let track = [1,2,3];
    res.push(track);
    track.push(4);
    
    console.log(track); // [1,2,3,4]
    console.log(res); //[1,2,3,4]
    
    
    res = [];
    track = [1,2,3];
    res.push([...track]);
    
    track.push(4);
    
    console.log(track); // [1,2,3,4]
    
    console.log(res); //[1,2,3]