Javascript Solution | Recursive


  • 0

    This solution uses the given API in the problem. The idea is to flatten the list, track the depth at each level and calculate the sum recursively

    var depthSum = function(nestedList) {
        var depthCounter = 1;
        var sum = 0;
        
        // Recursive function to flatten the list, track depth, and calculate sum
        function flatList (list, depthCounter) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].isInteger()) {
                    sum += list[i].getInteger() * depthCounter;
                } else {
                    flatList(list[i].getList(), depthCounter + 1);
                }
            }
        }
    
        // Flatten the list, add the elements
        flatList(nestedList, depthCounter);
        return sum;
    };

  • 0

    This solution does the same thing, but doesn't rely on the APIs given.

    var depthSum = function(nestedList) {
    
        var depthCounter = 1;
        var sum = 0;
    
        function flatList (list, depthCounter) {
            for (var i = 0; i < list.length; i++) {
                if (Array.isArray(list[i])) {
                    flatList(list[i], depthCounter + 1);
                } else {
                    sum += list[i] * depthCounter;
                }
            }
        }
    
        flatList(nestedList, depthCounter);
    
        return sum;
    };

Log in to reply
 

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