Coding questions · LinkedIn
Compute inverse-depth weighted sum of nested lists
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.
Inverse-Depth Weighted Sum of a Nested List
You are given a nested list of integers. Each element is either:
- an integer, or
- another nested list.
Define the depth of an integer as the number of lists it is inside (top-level integers have depth 1).
Compute the inverse-depth weighted sum:
- Let
Dbe the maximum depth in the structure. - An integer at depth
dhas weightD - d + 1. - Return the sum of
value * weightover all integers.
Input
- A nested list structure (you may assume an interface like:
isInteger(),getInteger(),getList()), or an equivalent representation.
Output
- An integer: the inverse-depth weighted sum.
Example
Input: [1, [4, [6]]]
- Depths:
1at depth 1,4at depth 2,6at depth 3. Max depthD=3. - Weights: depth1 -> 3, depth2 -> 2, depth3 -> 1
- Sum =
1*3 + 4*2 + 6*1 = 17
Constraints
- Total number of integers across all lists can be up to e.g.
10^4. - Integers fit in 32-bit signed range.
Inverse-Depth Weighted Sum of a Nested List
You are given a nested list of integers. Each element is either an integer or another nested list.
Define the depth of an integer as the number of lists it is inside (top-level integers have depth 1).
Compute the inverse-depth weighted sum:
- Let
Dbe the maximum depth present in the structure. - An integer at depth
dhas weightD - d + 1(so the deepest integers get weight 1, and shallower integers get larger weights). - Return the sum of
value * weightover all integers.
The input is provided as a nested list (a list whose elements are integers or further nested lists).
Example
Input: [1, [4, [6]]]
- Depths:
1at depth 1,4at depth 2,6at depth 3, so max depthD = 3. - Weights: depth 1 -> 3, depth 2 -> 2, depth 3 -> 1.
- Sum =
1*3 + 4*2 + 6*1 = 17.
Return 17.
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.