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
Nested List Weight Sum II - BFS Approach INPUT nestedList = [1, [4, 6]] root 1 depth=1 list 4 depth=2 6 depth=2 maxDepth = 2 Weight = maxDepth - depth + 1 depth 1: weight=2, depth 2: weight=1 ALGORITHM STEPS (BFS) 1 BFS Level Traversal Queue: [1, [4,6]] Process level by level 2 Find Max Depth Level 1: element 1 Level 2: elements 4, 6 maxDepth = 2 3 Calculate Weights 1: weight = 2-1+1 = 2 4: weight = 2-2+1 = 1 6: weight = 2-2+1 = 1 4 Sum Weighted Values 1*2 + 4*1 + 6*1 = 2 + 4 + 6 = 12 BFS processes outer to inner Shallower = Higher Weight FINAL RESULT Weighted Sum Calculation: 1 x 2 = 2 4 x 1 = 4 6 x 1 = 6 + 12 OK - Correct Answer! Output: 12 Key Insight: BFS naturally processes elements level by level. In this "inverted" weight problem, shallower elements get higher weights. First find maxDepth, then weight = maxDepth - depth + 1. Time: O(n), Space: O(n) where n is total number of nested elements. TutorialsPoint - Nested List Weight Sum II | BFS Approach
Asked in
LinkedIn 35 Facebook 28 Google 22
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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