Naive two-pass JavaScript recursion using reduce


  • 0
    var depthSumInverse = function(nestedList) {
        const maxDepth = nestedList.reduce((max, list) => Math.max(max, getMaxDepth(list)), 1);
        return nestedList.reduce((total, list) => total + sum(list, maxDepth), 0);
    };
    
    function getMaxDepth(nestedList) {
        if (nestedList.isInteger()) return 1;
        return nestedList.getList().reduce((max, list) => Math.max(max, 1 + getMaxDepth(list)), 1);
    }
    
    function sum(nestedList, n) {
        if (nestedList.isInteger()) return n * nestedList.getInteger();
        return nestedList.getList().reduce((total, list) => total + sum(list, n - 1), 0);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.