Level Up Your Coding Skills & Crack Interviews — Save up to 50% or more on Educative.io Today! Claim Discount

Arrow
Table of contents

339. Nested List Weight Sum

Problem Statement

This problem gives you a nested list of integers called nestedList, where each element is represented by the NestedInteger interface. An element can be either:

  • A single integer, or
  • A list of more NestedInteger elements (which may themselves be integers or further lists).

Your task is to compute a depth-weighted sum of all integers contained anywhere inside this structure:

  • The depth of an integer is the number of lists that contain it.
  • An integer that appears at the top level (not inside any inner list) has depth 1.
  • If an integer is inside one additional list, its depth is 2, and so on.

For every integer value x found in nestedList, you add x * depth(x) to the total. Finally, you return the total weighted sum as an integer.

Constraints:

  • $ \leq$ nestedList.length $\leq $
  • 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$.

Examples

InputOutputExplanation
[1,[2,[3]]]14Depths: 1*1 + 2*2 + 3*3 = 14
[[-1],[-2,[-3]]]-15Depths: (-1)*2 + (-2)*2 + (-3)*3 = -15
[[],[5],[[6,7],8]]65Empty lists add nothing; compute each integer with its depth, i.e., (5)*2 + (6)*3 + (7)*3 + (8)*2 = -15

Optimal Solution: Breadth-first Traversal

The main idea behind this optimal solution is to compute the weighted sum directly while traversing the nested structure. The key observation is that depth increases one level at a time: elements visible at the outermost level have depth $1$, and elements discovered by opening those lists belong to depth $2$, then depth $3$, and so on.

Breadth-first traversal (BFS) matches this perfectly because it processes items level by level using a queue. By working level-by-level, you always know which depth you are currently handling, so each integer can be weighted correctly at the moment it is encountered. Lists themselves do not add to the sum, but they serve as gateways to nested elements; once a list is expanded, its contents belong to the next depth level and should be processed with a larger multiplier.

A useful way to preserve correct depth values is to treat each level as a separate “batch” of work. The queue holds the current batch, and measuring its size at the start of a level ensures that everything processed in that pass belongs to the same depth. Any elements discovered while expanding lists are added to the queue for the next batch, automatically shifting them to the next depth without needing to store explicit (value, depth) pairs. This keeps the solution clean and single-pass, with memory usage limited to the queue of pending elements rather than an extra flattened copy of the input. As a result, the algorithm stays a single pass over the nested structure, and the only extra memory it uses is the queue needed to hold elements waiting to be processed, rather than an additional flattened representation of the entire input.

Algorithmic Steps

The algorithm is implemented as follows:

  1. Create a queue q.
  2. Initialize q by adding every element from nestedList in it.
  3. Set depth = 0 and total = 0.
  4. While the q is not empty:
    1. Increment depth by 1.
    2. Set layerSize to the length of q.
    3. Start iterating over nestedList:
      1. Pop an element from q and store it in cur.
      2. If cur is an integer, add value * depth to total.
      3. Otherwise, push all elements of its inner list into q.
  5. After iterating through , return the value of total.

Let’s look at the following illustration to get a better understanding of the solution:

1 / 8

Python Implementation

Let’s implement the algorithm as discussed above:

Time Complexity

The time complexity of the solution is $O(N)$ because each nested element (integer or list) is added to the queue and processed at most once, and each list’s children are iterated exactly once when that list is expanded.

Space complexity

The space complexity of the solution is $O(W)$ because the queue stores the elements of the current and upcoming levels, where $W$ is the maximum number of items held in the queue at any time (the widest level); in the worst case, this becomes $O(N)$.

Interview Tips & Tricks

A few practical notes that tend to matter in interviews:

  • Depth starts at level 1, not 0: This is the most common off-by-one mistake.
  • Empty lists are valid: They contribute nothing but still appear in traversal.
  • Negative integers are allowed: Don’t assume sums are non-negative.
  • Recursion vs. iteration: Recursion is clean here, but an iterative BFS (using a queue with depth levels) is a good backup if a language has tight recursion limits.
  • Mental model: Think of it as a tree where “going down one edge” increases depth by 111, and every integer node pays a “depth tax.”

Share with others:

Leave a Reply

Your email address will not be published. Required fields are marked *