Nested List Weight Sum II

Find max depth, then weight each integer by (maxDepth - itsDepth + 1).

Medium
Time O(N) Space O(D)
LeetCode
4 min read
tree dfs nested-list

Problem#

Given a nested list of integers, return the sum of each integer multiplied by its weight — where the weight of a value at depth d is maxDepth - d + 1 (leaves are heaviest).

Examples#

  • [[1,1],2,[1,1]]8 (depth-1 weight=2 for the 2’s; depth-2 weight=1 for the four 1’s)
  • [1,[4,[6]]]17

Constraints#

  • 1 <= nestedList.length <= 50.

Approach#

Two-pass: first compute the maximum nesting depth, then traverse again summing value * (maxDepth - depth + 1).

Solution#

Nested List Weight Sum II
class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
int maxDepth = 0;
function<void(vector<NestedInteger>&, int)> measure = [&](vector<NestedInteger>& list, int d) {
maxDepth = max(maxDepth, d);
for (auto& ni : list) if (!ni.isInteger()) measure(ni.getList(), d + 1);
};
measure(nestedList, 1);
int sum = 0;
function<void(vector<NestedInteger>&, int)> add = [&](vector<NestedInteger>& list, int d) {
for (auto& ni : list) {
if (ni.isInteger()) sum += ni.getInteger() * (maxDepth - d + 1);
else add(ni.getList(), d + 1);
}
};
add(nestedList, 1);
return sum;
}
};

Editorial#

The weight at depth d is maxDepth - d + 1, so leaves (deepest) get weight 1 and shallowest get the max weight. Computing depth requires a full traversal; doing it in two passes is cleaner than a single accumulator trick.

Complexity#

  • Time: O(N) where N is total elements.
  • Space: O(D) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.