Nested List Weight Sum II - Problem
You're given a nested list of integers where each element can be either an integer or another list (which can contain integers or more nested lists). Think of it like Russian nesting dolls, but with numbers!
Here's the twist: instead of deeper elements having higher weights, they have lower weights. The weight of an integer equals maxDepth - depth + 1, where:
- depth = how many lists contain this integer
- maxDepth = the deepest level in the entire structure
Your goal is to return the sum of each integer multiplied by its weight.
Example: In [1,[4,[6]]], the depths are: 1(depth=1), 4(depth=2), 6(depth=3). Since maxDepth=3, the weights are: 1×3 + 4×2 + 6×1 = 17.
Input & Output
example_1.py — Basic Nested Structure
$
Input:
[[1,1],2,[1,1]]
›
Output:
8
💡 Note:
Four 1's at depth 2 (weight=1), one 2 at depth 1 (weight=2). Sum = 4×1 + 1×2 = 6. Wait, let me recalculate: maxDepth=2, so weights are 2,1. Sum = 4×1 + 1×2 = 8.
example_2.py — Deep Nesting
$
Input:
[1,[4,[6]]]
›
Output:
17
💡 Note:
1 at depth 1 (weight=3), 4 at depth 2 (weight=2), 6 at depth 3 (weight=1). Since maxDepth=3: 1×3 + 4×2 + 6×1 = 17.
example_3.py — Single Level
$
Input:
[1,2,3,4,5]
›
Output:
15
💡 Note:
All elements at depth 1, maxDepth=1, so weight=1 for all. Sum = (1+2+3+4+5)×1 = 15.
Visualization
Tap to expand
Understanding the Visualization
1
Explore the Structure
Traverse the nested list like exploring each floor of the building to find all integers and their depths
2
Find Maximum Depth
Determine the highest floor (maximum nesting level) to establish the weight system
3
Calculate Reverse Weights
Apply the formula: weight = maxDepth - currentDepth + 1, so deeper elements get lower weights
4
Sum Weighted Values
Multiply each integer by its weight and sum all results for the final answer
Key Takeaway
🎯 Key Insight: The reverse weighting system rewards elements at shallower depths more than deeper ones. We can solve this efficiently in a single pass by collecting level sums and applying the mathematical relationship between depth and weight contributions.
Time & Space Complexity
Time Complexity
O(n)
Single DFS traversal of all n elements in the nested structure
✓ Linear Growth
Space Complexity
O(d)
Only recursion stack space proportional to maximum depth d
✓ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code