Show problems as
Classic problem #339MediumDepth-First SearchBreadth-First Search

Nested List Weight Sum

Real-world version: Tiered Ledger Adjustments
Tracked in this browser only
Read Nested List Weight Sum on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

An auditor hands you a file of ledger adjustments, grouped and regrouped by department. The file is supplied as JSON: entries is a list, and each slot in a list holds either a signed integer, which is one adjustment, or a further list, which is a nested group. A group is allowed to be empty.

The tier of an adjustment is the number of groups wrapped around it. Adjustments written straight into entries sit at tier 1, adjustments inside a group that sits straight in entries are at tier 2, and each further layer of nesting adds one.

Return the sum of value * tier over every adjustment the file contains.

Examples

Example 1

Input
entries = [3,[5,-2],7]
Output
16

The adjustments 3 and 7 sit at tier 1, while 5 and -2 sit at tier 2, giving 3 + 7 + 2*5 + 2*(-2) = 16.

Example 2

Input
entries = [[[4]]]
Output
12

Three groups wrap the single adjustment 4, so its tier is 3 and the total is 3*4 = 12.

Example 3

Input
entries = [-8]
Output
-8

One tier-1 adjustment, and adjustments may be negative, so the total is 1*(-8) = -8.

Example 4

Input
entries = [2,[3,[-1,[6]]]]
Output
29

The tiers are 1 for 2, 2 for 3, 3 for -1 and 4 for 6, giving 2 + 2*3 + 3*(-1) + 4*6 = 29.

Example 5

Input
entries = [[],9]
Output
9

The empty group holds no adjustments and contributes nothing, leaving the tier-1 adjustment 9.

Constraints

  • 1 <= entries.length <= 50
  • Every adjustment is in the range [-100, 100].
  • No adjustment sits at a tier greater than 50.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def depth_sum(entries: list) -> int:
Java
public int depthSum(List<NestedInteger> entries)