FastPrepParse and Sum a Depth-Weighted Nested List

Parse and Sum a Depth-Weighted Nested List

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given a valid bracketed string nestedList representing a nested list of signed integers. Lists use square brackets, elements are comma-separated, and optional spaces may appear anywhere outside an integer token.

The outermost list has depth 1. Each nested list increases the depth of its integer elements by one. Return the sum of every integer multiplied by its depth.

Your parser must handle multi-digit values, optional minus signs, closing brackets, and an integer immediately followed by the end of the string.

Function

depthSum(nestedList: String) → int

Examples

Example 1

nestedList = "[3, 8, [2, 14], [2, [91]]]"return = 320

The weighted sum is 3 + 8 + 2*2 + 14*2 + 2*2 + 91*3 = 320.

Example 2

nestedList = "[1,[4,[6]]]"return = 27

The weighted sum is 1*1 + 4*2 + 6*3 = 27.

Example 3

nestedList = "[-12, [5], 10]"return = 8

The integers contribute -12*1 + 5*2 + 10*1 = 8.

Constraints

  • nestedList is a syntactically valid list expression.
  • Every integer token fits in a signed 32-bit integer.
  • The final weighted sum fits in a signed 32-bit integer.

More Google problems

See Google hiring insights
public int depthSum(String nestedList) {
    // Write your code here.
}
nestedList"[3, 8, [2, 14], [2, [91]]]"
expected320
Checking account…