KatInterview

Bracket Depth Scoring of a Nested Integer String

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringsstring-parsingnested-structuressingle-pass

Last 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 adds 0.
  • 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 0 to 10^6.
  • s is 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.