Nested List Weight Sum II Problem
Description
LeetCode Problem 364.
You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.
The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Let maxDepth be the maximum depth of any integer.
The weight of an integer is maxDepth - (the depth of the integer) + 1.
Return the sum of each integer in nestedList multiplied by its weight.
Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1's with a weight of 1, one 2 with a weight of 2.
1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8
Example 2:

Input: nestedList = [1,[4,[6]]]
Output: 17
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1.
1*3 + 4*2 + 6*1 = 17
Constraints:
1 <= nestedList.length <= 50- The values of the integers in the nested list is in the range
[-100, 100]. - The maximum depth of any integer is less than or equal to
50. - There are no empty lists.
Solution
Approach: One DFS with Two Sums
The weight of an integer, maxDepth - depth + 1, depends on maxDepth, and we only know that after seeing the whole list. One option is two passes: find maxDepth first, then add everything up. A little algebra lets one pass do it.
For integers a at depths d, the answer is the sum of a * (maxDepth + 1 - d), which is
(maxDepth + 1) * (sum of a) - (sum of a * d).
So a single depth-first search can collect three things: the deepest depth seen (maxDepth), the plain sum of all integers (total), and the depth-weighted sum (weighted). Every element of the top-level list starts at depth 1. When the search meets an integer, it adds it to total and a * depth to weighted. When it meets a list, it visits each element at depth + 1. At the end, return (maxDepth + 1) * total - weighted.
Check this with [1,[4,[6]]]: maxDepth = 3, total = 11, weighted = 1*1 + 4*2 + 6*3 = 27, and 4 * 11 - 27 = 17.
Complexity: O(N) time, where N is the number of integers and lists in the input. O(D) space for the recursion, where D is the maximum depth.
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
# answer = sum of a * (maxDepth - depth + 1) = (maxDepth + 1) * total - weighted,
# where total = sum of a and weighted = sum of a * depth
max_depth = total = weighted = 0
def dfs(x: NestedInteger, depth: int) -> None:
nonlocal max_depth, total, weighted
max_depth = max(max_depth, depth)
if x.isInteger():
total += x.getInteger()
weighted += x.getInteger() * depth
else:
for y in x.getList():
dfs(y, depth + 1)
for x in nestedList:
dfs(x, 1)
return (max_depth + 1) * total - weighted