Nested List Weight Sum - Problem

Imagine you have a nested list where each element can be either an integer or another list containing more integers and lists. Your task is to calculate a weighted sum where each integer is multiplied by its depth (how many levels deep it is nested).

The depth starts at 1 for the outermost level. For example, in [1,[2,2],[[3],2],1]:

  • The integers 1 (first and last) are at depth 1
  • The integers 2,2 and the second 2 are at depth 2
  • The integer 3 is at depth 3

So the weighted sum would be: 1×1 + 2×2 + 2×2 + 3×3 + 2×2 + 1×1 = 1 + 4 + 4 + 9 + 4 + 1 = 23

Goal: Return the sum of each integer multiplied by its depth.

Input & Output

example_1.py — Simple nested list
$ Input: nestedList = [1,[2,2],[[3],2],1]
Output: 23
💡 Note: 1×1 + 2×2 + 2×2 + 3×3 + 2×2 + 1×1 = 1 + 4 + 4 + 9 + 4 + 1 = 23. The first and last 1 are at depth 1, the three 2's are at depth 2, and the 3 is at depth 3.
example_2.py — Deeper nesting
$ Input: nestedList = [[1,1],2,[1,1]]
Output: 10
💡 Note: 1×2 + 1×2 + 2×1 + 1×2 + 1×2 = 2 + 2 + 2 + 2 + 2 = 10. The four 1's are at depth 2 (inside nested lists), and the 2 is at depth 1.
example_3.py — Single level
$ Input: nestedList = [1,2,3,4,5]
Output: 15
💡 Note: 1×1 + 2×1 + 3×1 + 4×1 + 5×1 = 1 + 2 + 3 + 4 + 5 = 15. All integers are at depth 1 since there's no nesting.

Visualization

Tap to expand
Floor 1 (Depth 1)[1, [2,2], [[3],2], 1] → Collect: 1×1 + 1×1 = 2Floor 2 (Depth 2)[2,2] and [3],2 → Collect: 2×2 + 2×2 + 2×2 = 12Floor 3 (Depth 3)[3] → Collect: 3×3 = 9Total: 2 + 12 + 9 = 23
Understanding the Visualization
1
Enter Building
Start at ground floor (depth 1) with the main list
2
Explore Each Room
For integers, collect value × floor; for nested lists, go deeper
3
Go Deeper
When entering nested lists, go up one floor (increment depth)
4
Collect Total
Sum all collected values from all floors
Key Takeaway
🎯 Key Insight: DFS allows us to calculate the weighted sum in one pass by tracking depth as we traverse, making it the most efficient solution with O(n) time and O(d) space complexity.

Time & Space Complexity

Time Complexity
⏱️
O(n)

We visit each element exactly once during the DFS traversal

n
2n
Linear Growth
Space Complexity
O(d)

Only the recursion stack space, where d is the maximum depth of nesting

n
2n
Linear Space

Constraints

  • 1 ≤ nestedList.length ≤ 50
  • The values of the integers in the nested list are in the range [-100, 100]
  • The maximum depth of any integer is less than or equal to 50
Asked in
LinkedIn 45 Google 38 Amazon 32 Facebook 28 Microsoft 22
78.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen