Compute inverse-depth weighted sum of nested lists
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of nested list traversal, depth computation, and weighted aggregation by the inverse of depth, focusing on concepts like maximum depth calculation and applying weights across hierarchical integer elements.
Constraints
- Total number of integers across all lists can be up to ~10^4.
- Integers fit in 32-bit signed range.
- An empty top-level list returns 0.
- Deeper integers receive smaller weights; the deepest integers always have weight 1.
Examples
Input: ([1, [4, [6]]],)
Expected Output: 17
Explanation: D=3. 1 at depth1 (w3), 4 at depth2 (w2), 6 at depth3 (w1): 1*3 + 4*2 + 6*1 = 17.
Input: ([[1, 1], 2, [1, 1]],)
Expected Output: 8
Explanation: D=2. 2 at depth1 (w2); four 1's at depth2 (w1): 2*2 + 4*1 = 8.
Input: ([1, [4, [6]], [7]],)
Expected Output: 31
Explanation: D=3. 1 at depth1 (w3), 4 at depth2 (w2), 7 at depth2 (w2), 6 at depth3 (w1): 3 + 8 + 14 + 6 = 31.
Input: ([],)
Expected Output: 0
Explanation: Empty structure: no integers, sum is 0.
Input: ([5],)
Expected Output: 5
Explanation: D=1, single integer at depth1 (w1): 5*1 = 5.
Input: ([[[[10]]]],)
Expected Output: 10
Explanation: Only one integer at the deepest level (weight 1 regardless of D): 10*1 = 10.
Input: ([-3, [-2, [-1]]],)
Expected Output: -14
Explanation: D=3. -3*3 + -2*2 + -1*1 = -9 - 4 - 1 = -14; negatives are handled normally.
Input: ([0, [0, [0]]],)
Expected Output: 0
Explanation: All zeros contribute nothing regardless of weight: sum is 0.
Hints
- Two passes are simplest: first compute the maximum depth D, then sum value * (D - depth + 1).
- Alternatively, run a BFS level by level, keep a running 'unweighted' accumulator that carries each level's prefix sum forward; the total accumulates each integer once per remaining level, which equals weighting by (D - depth + 1).
- Top-level integers are at depth 1, not depth 0 — be careful with the off-by-one in the weight formula.