← Questions
Nested list weight sum
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Feb 2026. It tests recursion and dfs.
A nested list holds integers and other nested lists, to any depth. Return the sum of every integer multiplied by its depth. Integers directly in the outer list have depth 1, those inside one inner list have depth 2, and so on.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
depth_sum(nested: list) -> int— each element is anintor alistof the same kind. An empty list returns0.
Example
[1, [4, [6]]] -> 27 # 1*1 + 4*2 + 6*3
[[1, 1], 2, [1, 1]] -> 10 # four 1s at depth 2, one 2 at depth 1
[] -> 0
[[[]]] -> 0
Constraints
- Up to
10^5integers in total; nesting up to about10^3levels. - Integers may be negative.
Clarifying questions
- Is the input plain lists, or a
NestedIntegerinterface withis_integer(),get_integer()andget_list()? - Can lists be empty?
- Can the nesting be deep enough to overflow the recursion stack?
What a strong answer covers
- DFS passing the current depth down: an integer adds
value * depth, a list recurses withdepth + 1. - BFS by level as an alternative, multiplying the sum of each level by its depth.
- An explicit stack of
(list, depth)when nesting is too deep for recursion. -
O(N)time over all integers and lists,O(D)extra space for depthD. - Tests: empty list, empty inner lists, negative values, a single deep chain.
Follow-ups
- Inverse weights: the deepest integers get weight 1 and the outer ones the largest weight. Can you do it in one pass?
- The input arrives as a string such as
"[1,[4,[6]]]". Parse it and compute the sum. - Flatten the nested list into an iterator that returns integers one at a time.
Where it's asked
- Meta · AI-enabled coding · Last asked Feb 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
recursion · dfs
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
