Compute weighted sum of nested lists
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Compute weighted sum of nested lists states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- Each element of the collection is either an integer or a nested list of such elements.
- Nesting depth >= 1; the top-level list is depth 1.
- Integers may be negative, zero, or positive.
- The collection may be empty, in which case the sum is 0.
Examples
Input: ([[1,1],2,[1,1]],)
Expected Output: 10
Explanation: 2 at depth 1 (=2) plus four 1s at depth 2 (=8) gives 10.
Input: ([1,[4,[6]]],)
Expected Output: 27
Explanation: 1*1 + 4*2 + 6*3 = 1 + 8 + 18 = 27.
Input: ([],)
Expected Output: 0
Explanation: Empty collection contributes 0.
Input: ([5],)
Expected Output: 5
Explanation: Single integer at depth 1: 5*1 = 5.
Input: ([[[[3]]]],)
Expected Output: 12
Explanation: 3 is nested four levels deep: 3*4 = 12.
Input: ([-1,[-2,[-3]]],)
Expected Output: -14
Explanation: -1*1 + -2*2 + -3*3 = -1 - 4 - 9 = -14, confirming negatives work.
Input: ([0,[0,[0]]],)
Expected Output: 0
Explanation: All zeros sum to 0 regardless of depth weighting.
Input: ([[1,[2,[3,[4]]]]],)
Expected Output: 40
Explanation: 1*2 + 2*3 + 3*4 + 4*5 = 2 + 6 + 12 + 20 = 40 (asymmetric deep nesting).
Hints
- DFS: recurse into each sublist carrying the current depth; when you hit an integer, add value * depth.
- BFS: process the structure level by level with a queue; everything dequeued at level L contributes value * L. Increment the depth after each level is fully processed.
- Inverted weighting (deepest level = weight 1): first compute the maximum depth, then weight each integer by (maxDepth - depth + 1). This can also be done in a single BFS pass by accumulating an unweighted running total at each level and re-adding it every subsequent level — a clever O(n) one-pass trick.
- Watch the base case: an empty list contributes 0, and a single integer at the top level is weighted by depth 1.