Nested Weight Sum
EasyDFS · LinkedIn
You are given nested, a Python list whose elements are either integers or other lists of the same kind (lists can be nested to any depth, and can be empty).
The depth of an integer is the number of lists that contain it: integers directly in nested have depth 1, integers inside a list inside nested have depth 2, and so on. Return the sum of every integer multiplied by its depth.
For example, in [1, [2, [3]]] the depths are 1, 2 and 3, so the answer is 1*1 + 2*2 + 3*3 = 14. Empty lists contribute 0.
Example 1
- Input:
- nested = [3,[2,[1,4]],-1]
- Output:
- 21
- Explanation
- 3 and -1 are at depth 1, 2 is at depth 2, and 1 and 4 are at depth 3. The total is 3*1 + 2*2 + (1 + 4)*3 + (-1)*1 = 21.
Example 2
- Input:
- nested = [[1],[2],[3]]
- Output:
- 12
- Explanation
- Each integer sits inside one inner list, so each is at depth 2: (1 + 2 + 3) * 2 = 12.
Example 3
- Input:
- nested = [[],[[5]]]
- Output:
- 15
- Explanation
- The empty list contributes nothing. 5 is inside two lists beneath the top level, so it is at depth 3 and contributes 15.
Constraints
0 <= total number of integers <= 10^4-100 <= each integer <= 100- Maximum nesting depth of any integer is
50