Magicsheet logo

Nested List Weight Sum

Medium
52.5%
Updated 6/1/2025

Nested List Weight Sum

What is this problem about?

The Nested List Weight Sum problem gives you a nested list where each element is either an integer or a list of integers/lists. Each integer is multiplied by its depth level (depth 1 for top-level integers, depth 2 for those inside one list, etc.). Return the sum of all integers multiplied by their respective depths. This Nested List Weight Sum coding problem tests recursive DFS or BFS on nested structures.

Why is this asked in interviews?

Apple, Meta, Amazon, LinkedIn, and Google ask this because nested data structures appear throughout real software — JSON parsing, file system traversal, and compiler ASTs. The BFS and DFS interview pattern is directly applied here, and the problem tests clean recursive thinking on variable-depth structures.

Algorithmic pattern used

Recursive DFS with depth parameter. Define dfs(list, depth). For each element: if it's an integer, add element * depth to the total. If it's a list, recursively call dfs(sublist, depth+1). Alternatively, BFS level by level — process all elements at depth d before moving to depth d+1.

Example explanation

Nested list: [[1,1],2,[1,1]].

  • [1,1] at depth 1 → recurse into it at depth 2: 12 + 12 = 4.
  • 2 at depth 1 → 2*1 = 2.
  • [1,1] at depth 1 → recurse: 12 + 12 = 4. Total = 4+2+4 = 10.

Common mistakes candidates make

  • Not passing depth correctly when recursing into nested lists.
  • Using depth 0 as the top level instead of depth 1.
  • Treating a nested list element as an integer (failing to check isInteger()).
  • Forgetting that the input itself is a list at depth 1 (not depth 0).

Interview preparation tip

Nested structure problems require clean recursive decomposition. Always think in terms of "what to do with an integer" and "what to do with a list" — two cases, handled separately. The NestedInteger interface provides isInteger(), getInteger(), and getList() methods. Practice implementing both recursive DFS and iterative BFS for nested lists, as interviewers sometimes ask for both approaches to the same problem.

Similar Questions