1035. Depth-Weighted Total

A warehouse catalogue lists parcels. A parcel is either a single crate with a declared value, or a container that holds more parcels, which may themselves be containers. The list items mirrors that structure: each entry is an integer (a crate) or a list of further entries (a container). Entries directly inside items sit at depth 1, and anything inside a container at depth d sits at depth d + 1.

Handling a crate costs its value multiplied by its depth. Return the total handling cost of every crate in items. Containers cost nothing by themselves, and empty containers contribute 0. Values can be negative (credits).

Aim for O(n) time over all entries and O(d) extra space, where d is the deepest nesting level.

Example 1

Input:
items = [3,[2,[5]],4]
Output:
26
Explanation:

3 and 4 are at depth 1, 2 is at depth 2 and 5 at depth 3, giving 3 + 4 + 4 + 15 = 26.

Example 2

Input:
items = [[[-2]],7]
Output:
1
Explanation:

-2 sits three levels deep and contributes -6, while 7 sits at depth 1, so the total is 1.

Example 3

Input:
items = [[1,[2]],[3]]
Output:
14
Explanation:

1 and 3 are at depth 2 (2 + 6) and 2 is at depth 3 (6), so the total is 14.

Constraints

The total number of integers and lists across all levels is at most 3 * 104.

The nesting depth is at most 100.

-100 ≤ each integer ≤ 100. The answer always fits in a 32-bit signed integer.

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(d)

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…