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.
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.