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,2and the second2are at depth 2 - The integer
3is 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.
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
Visualization
Tap to expand
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code