1682. Level Totals of a Nest

A rental company stores its equipment catalogue as a nest of boxes: nestedList holds integers (stock counts) and boxes, and every box can hold more integers and more boxes. Integers that sit directly in nestedList are at depth 1, integers inside a box of nestedList are at depth 2, and so on.

Return an integer array totals where totals[d-1] is the sum of all integers at depth d, for every d from 1 to D, where D is the deepest depth that contains at least one integer. A depth between 1 and D that has no integers reports 0. If there are no integers at all, return an empty array. Aim for O(n) time and O(depth) extra space, where n counts all integers and boxes.

Example 1

Input:
nestedList = [1,[4,[6]]]
Output:
[1,4,6]
Explanation:

The 1 is at depth 1, the 4 at depth 2 and the 6 at depth 3, so the totals are 1, 4 and 6.

Example 2

Input:
nestedList = [[1,1],2,[1,1]]
Output:
[2,4]
Explanation:

Only the 2 is at depth 1, while the four 1s are at depth 2, giving [2, 4].

Example 3

Input:
nestedList = [[[5]],3]
Output:
[3,0,5]
Explanation:

Depth 1 holds 3, depth 2 holds no integers so it reports 0, and depth 3 holds 5.

Constraints

At most 1000 integers and lists in total; nesting depth ≤ 50; -104 ≤ value ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(depth)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…