Bracket Depth Scoring of a Nested Integer String
StringsAuto-graded · 20 test casesLast updated
Scan a bracketed string of non-negative integers and sum each integer times its bracket nesting level, handling multi-digit numbers, whitespace and empty lists.
Nested Bracket Scoring
You receive a text s that describes a well-formed nested list of non-negative integers. A list is written between [ and ], and its items are separated by commas. Each item is either an integer or another list.
The outermost list sits at level 1. A list found directly inside a list at level L sits at level L + 1. An integer takes the level of the list that directly contains it.
Your task is to return the score of the text: the sum, over every integer in it, of the integer's value multiplied by its level.
Rules
- Space characters may appear anywhere between tokens and must be ignored.
- An empty list (such as
[]or[ ]) contains no integers and adds0. - Integers can have several digits (for example
123), and must be read as a whole number, not digit by digit. - A number may be directly followed by
]or,; it still belongs to the list it is inside.
Function
Implement depth_weighted_sum(s) that takes the string s and returns the score as an integer.
Constraints
2 <= len(s) <= 10^5- Every integer is in the range
0to10^6. sis guaranteed to be a valid nested list representation.- The nesting level never exceeds
10^4.
Examples
Example 1
Input: depth_weighted_sum('[[1, 1], 2, [1, 1]]')
Output: 10
Example 2
Input: depth_weighted_sum('[1, [4, [6]]]')
Output: 27
Example 3
Input: depth_weighted_sum('[10, [ ], [20, [30]]]')
Output: 140
Hints
Hint 1
The nesting structure does not need to be built. An integer's weight depends only on how many `[` are currently open when you read it.
Hint 2
Keep a running counter that goes up on `[` and down on `]`. When you meet a digit, read the entire run of consecutive digits as one number before looking at the next character.
Hint 3
Add the number times the counter right after reading the digits, before any following `]` lowers the counter. Avoid recursion, since the depth can reach 10^4.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
No tree is needed. An integer's weight is the number of [ that are open at the moment it is read, so a single left-to-right scan with two variables is enough:
depth: incremented on[, decremented on].total: the running answer.
When the scan hits a digit, it consumes the whole run of consecutive digits as one number (building it with value * 10 + digit), then adds value * depth to total. Commas, spaces and any other characters are skipped.
Why it is correct
- Depth invariant: at any position,
depthequals the number of unmatched[before it. The outermost[makes it 1, each nested[adds 1, and each]returns to the parent's value. - Number boundaries: in valid input, a maximal run of digits is exactly one integer, since integers are separated by commas, brackets or spaces.
- Correct weight: the number is fully read and added before the next
]is processed, so it is weighted by the depth of the list that directly contains it, even in cases like[123]. - Empty lists:
[]raises and lowersdepthwithout any digits in between, so they add nothing.
Check on "[10, [ ], [20, [30]]]": 10 at depth 1 gives 10, 20 at depth 2 gives 40, 30 at depth 3 gives 90, total 140.
Complexity
- Time: O(n), since each character is visited once and the index never moves backward.
- Space: O(1) extra. An iterative scan also avoids the
RecursionErrorthat a recursive parser could hit at depth 10^4.
Reference solution
def depth_weighted_sum(s: str) -> int:
depth = 0
total = 0
i = 0
n = len(s)
while i < n:
ch = s[i]
if ch == '[':
depth += 1
i += 1
elif ch == ']':
depth -= 1
i += 1
elif ch.isdigit():
value = 0
while i < n and s[i].isdigit():
value = value * 10 + int(s[i])
i += 1
total += value * depth
else:
i += 1
return total