# Javascript Solution | Two pass

• The inline comments should explain what the code does.

The idea is to recursively calculate the sum of all elements at each depth and store them in a "hash" javascript object.

During this call, we also calculate the maximum depth reached.

We then just go through the object to calculate the sum, using the depth that was calculated.

var depthSumInverse = function(nestedList) {
var depthCounter = 1;
var hash = {};
var sum = 0;
var depth = 1;

function flatList (list, depthCounter) {
for (var i = 0; i < list.length; i++) {
if (!list[i].isInteger()) {
// Keep going deep into the list
flatList(list[i].getList(), depthCounter + 1);
} else {
// The hash map contains the sum of each element in the array
// at that depth
if (!hash[depthCounter]) {
hash[depthCounter] = 0;
}

// Calculate sum at each level
hash[depthCounter] += list[i].getInteger();

// Keep track of the maximum depth reached
depth = Math.max(depth, depthCounter);
}
}
}

// Recursively get the sum at each level
flatList(nestedList, depthCounter);

// At this point, "depth" is the max depth reached
// Now we calculate the required sum
var count = depth;
for (var i = 1; i <= depth; i++) {
// If the sum at depth "i" exists, total it up
if (hash[i]) {
sum += hash[i] * count;
}
// Reduce the depth count
count--;
}

return sum;
};

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