Nested List Weight Sum

Medium

Topics
DFSBFSStack

You are given a nested list of integers. Each element is either an integer or a list whose elements are themselves integers or lists.

The depth of an integer is the number of lists it sits inside. An integer at the top level has depth 1, an integer inside one list has depth 2, and so on.

Return the sum of every integer multiplied by its depth.

The list arrives as the string s that spells it, in the bracket notation below, because the judge reads a line of text rather than LeetCode’s NestedInteger objects. Parsing it is not the exercise.

Example 1

depth 12
depth 21111
An integer’s depth is the number of brackets it sits inside, so the rows regroup the same integers by how deeply they were nested rather than by which list they came from. Top-level integers count as depth 1, not 0. Weighting each row by its depth gives 2×1 + 4×2 = 10.
The nested list arrives as the string that spells it; each row collects the integers found at one depth.
Input:  s = "[[1,1],2,[1,1]]"
Output: 10
Explanation: Four 1s at depth 2 contribute 8, and the 2 at depth 1 contributes 2.

Example 2

depth 11
depth 24
depth 36
Weighting each row by its depth gives 1×1 + 4×2 + 6×3 = 27.
Input:  s = "[1,[4,[6]]]"
Output: 27
Explanation: 1 at depth 1, 4 at depth 2, 6 at depth 3: 1 + 8 + 18.

Example 3

depth 10
Weighting each row by its depth gives 0×1 = 0.
Input:  s = "[0]"
Output: 0
Explanation: A single zero contributes nothing at any depth.

Example 4

depth 45
Input:  s = "[[[[5]]]]"
Output: 20
Explanation: One integer, nested four deep.

Constraints

  • 1 <= number of integers <= 50
  • The maximum depth is at most 50
  • -100 <= integer value <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The depth of an integer is not a property of the integer — it is a property of where it was found. So the only thing the traversal has to do is carry the current depth down with it and hand each integer the depth it was reached at.

Spelled out that way it sounds like it needs the nested structure built first, and it does not. The depth of an integer is exactly how many brackets are still open at the moment it is read, so a single left-to-right scan that counts [ up and ] down already knows the weight of every number it passes. The bracket counter is the depth.

That also settles the awkward part of doing this outside Python and JavaScript: with no structure to build there is no JSON library to reach for.

Worth separating from its sibling problem. The inverse-weighting variant, where a value at depth d is weighted by maxDepth - d + 1, cannot be done in one scan, because the weight of the very first number is not known until the last bracket has been seen.

Approach

  1. Keep a running total and a bracket counter, both starting at zero.
  2. Scan the string. On [ raise the counter, on ] lower it. The counter is the depth of anything read next, so a top-level integer is read at depth 1 as the statement requires.
  3. On a digit or a minus sign, read the whole number — a minus belongs to the number that follows it, and a number may be several digits — and add its value times the current counter.
  4. Skip commas and anything else. The total after the scan is the answer.

Walkthrough

s = "[1,[4,[6]]]"

char   depth after   contribution
  [         1
  1         1          1 x 1 =  1
  ,         1
  [         2
  4         2          4 x 2 =  8
  ,         2
  [         3
  6         3          6 x 3 = 18
  ]         2
  ]         1
  ]         0

total 27

The two sibling lists in "[[1,1],2,[1,1]]" both sit at
depth 2 for the same reason: the counter goes back down
on the closing bracket before the second one opens.

Complexity

  • Time — O(n): one pass over the characters, each read once.
  • Space — O(1): a total and a counter, whatever the nesting depth. Building the structure first would cost O(n), and recursing over it O(d).

Common Pitfalls

  • Starting the depth at 0. The statement puts top-level integers at depth 1, and on a scan that means counting the outermost [ before reading anything.
  • Incrementing the depth per element rather than per bracket. Two sibling lists are at the same depth, not consecutive ones.
  • Reading one digit at a time, so 12 contributes as 1 and 2. Likewise a - belongs to the number after it, not to the number before.
  • Confusing this with the inverse-weight variant, where a value at depth d is weighted by maxDepth - d + 1. That one cannot be done in a single scan.

Full Solution — all languages

class Solution:
    def depthSum(self, s):
        total = 0
        depth = 0
        i = 0
        while i < len(s):
            c = s[i]
            if c == '[':
                depth += 1
                i += 1
            elif c == ']':
                depth -= 1
                i += 1
            elif c == '-' or c.isdigit():
                j = i + 1 if c == '-' else i
                while j < len(s) and s[j].isdigit():
                    j += 1
                total += int(s[i:j]) * depth
                i = j
            else:
                i += 1
        return total
SensAI
Beta
Tap the mic to stop voice mode