I'm trying to solve this problem "Nested List Weight Sum":
Problem:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)
This is my solution.
var depthSum = function (nestedList, sum=0, depth=1) { nestedList.forEach((val) => { if (Array.isArray(val)) { depth = depth+1; return depthSum(val, sum, depth); } else { sum += val * depth; } }); return sum;
};Not sure what I'm missing. When I debug it, at some point I get the answer but return sum does not kick in and i get a different answer.
Can someone point me the bug?
53 Answers
You could use Array#reduce and omit the sum for every level by returning a sum for each level.
function depthSum(nestedList, level = 1) { return nestedList.reduce((sum, val) => sum + (Array.isArray(val) ? depthSum(val, level + 1) : level * val), 0);
};
console.log(depthSum([[1, 1], 2, [1, 1]])); So one way to tackle it.
There's no sense in returning from inside your forEach, what you should instead do is add the total from the recursive call to your current total. And since you are doing that, you don't need to have the sum be a parameter to your depthSum function
var nestedList = [[1,1],2,[1,1]];
var depthSum = function(nestedList, depth = 1) { var sum = 0; nestedList.forEach((val) => { if (Array.isArray(val)) { sum += depthSum(val, depth + 1); } else { sum += val * depth; } }); return sum;
};
console.log(depthSum(nestedList)) As per the requirement of the code in Leetcode the following is the Working code.
var depthSum = function (nestedList, depth=1) { var res = 0; nestedList.forEach((val) => { if (val.isInteger() === false) { res += depthSum(val.getList(), depth + 1); } else { res += val.getInteger() * depth; } }); return res;
};You can't use Array.isArray() because all the members will return false. and also you can't access the values or list directly. You need to access through their API. The input to the function is not simply an array. See the input type and the APIs present from the specification as follow:
* function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */
/** * @param {NestedInteger[]} nestedList * @return {number} */