Nested List Weight Sum Problem
Description
LeetCode Problem 339.
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.
Return the sum of each integer in nestedList multiplied by its depth.
Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: 10
Explanation: Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.
Example 2:

Input: nestedList = [1,[4,[6]]]
Output: 27
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.
Example 3:
Input: nestedList = [0]
Output: 0
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.
Solution
Approach: Depth-First Search
The nested list is a tree: each list is a node, and its elements are its children. We just need every integer together with its depth, which a DFS carries along naturally.
Define dfs(items, depth) that returns the weighted sum of a list whose elements are at depth depth:
- For an integer element, add
value * depth. - For a list element, add
dfs(element.getList(), depth + 1), because its elements are one level deeper.
The answer is dfs(nestedList, 1): the top-level elements are inside one list, so they have depth 1. An empty inner list adds nothing.
For example 2, [1,[4,[6]]]: 1 is at depth 1, 4 at depth 2 and 6 at depth 3, giving 1*1 + 4*2 + 6*3 = 27.
Complexity: O(N) time, where N is the total number of integers and lists, and O(D) extra space for the recursion, where D is the maximum depth.
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def dfs(items: List[NestedInteger], depth: int) -> int:
total = 0
for item in items:
if item.isInteger():
total += item.getInteger() * depth
else:
total += dfs(item.getList(), depth + 1) # one list deeper
return total
return dfs(nestedList, 1)