Nested List Weight Sum II - Problem
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.
Let maxDepth be the maximum depth of any integer. The weight of an integer is maxDepth - (the depth of the integer) + 1.
Return the sum of each integer in nestedList multiplied by its weight.
Input & Output
Example 1 — Basic Nested Structure
$
Input:
nestedList = [1,[4,6]]
›
Output:
12
💡 Note:
Max depth is 2. Elements: 1 at depth 1 (weight 2), 4 at depth 2 (weight 1), 6 at depth 2 (weight 1). Sum = 1×2 + 4×1 + 6×1 = 12
Example 2 — Deeper Nesting
$
Input:
nestedList = [1,[2,2],[[3],2],1]
›
Output:
17
💡 Note:
Max depth is 3. Weights: depth 1→3, depth 2→2, depth 3→1. Sum = 1×3 + 2×2 + 2×2 + 3×1 + 2×2 + 1×3 = 17
Example 3 — Single Level
$
Input:
nestedList = [1,2,3]
›
Output:
6
💡 Note:
All elements at depth 1, weight = 1. Sum = 1×1 + 2×1 + 3×1 = 6
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Nested list [1,[4,6]] with varying depths
2
Process
Calculate weights: deeper = lighter weight
3
Output
Weighted sum = 12
Key Takeaway
🎯 Key Insight: Inverted weighting gives higher weights to shallower elements (opposite of traditional depth weighting)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code