FastPrepInverse-Depth Nested List Sum
Problem · String

Inverse-Depth Nested List Sum

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEPHONE SCREEN

Problem statement

A nested list contains signed integers and other lists. You receive its valid bracketed representation as nestedList. Compute an inverse-depth weighted sum.

An integer directly inside the outermost list has depth 1. Each enclosing nested list adds one. Let D be the greatest depth of any integer in the input. An integer with value x at depth d contributes x × (D - d + 1). Return the sum of all contributions as a 64-bit integer.

Lists use square brackets and comma-separated elements. An element is an integer or another list. Integers use ordinary base-10 notation, optionally preceded by a minus sign. There are no spaces, plus signs, or leading zeroes except the integer 0. The entire input is one list, and empty lists are allowed.

Empty lists contain no integers and do not increase D by themselves. If there are no integers anywhere, return 0. Repeated values are separate occurrences and each contributes to the sum.

Function

depthSumInverse(nestedList: String) → long

Examples

Example 1

nestedList = "[2,[3,[4]],5]"return = 31

The deepest integer is 4 at depth 3. The sum is 2×3 + 3×2 + 4×1 + 5×3 = 31.

Example 2

nestedList = "[-2,[5],[[[]]],0]"return = 1

The deepest integer is 5 at depth 2; the deeper empty lists do not count. The result is -2×2 + 5×1 + 0×2 = 1.

Constraints

  • 2 <= nestedList.length <= 5000.
  • The representation is valid under the stated grammar.
  • Every integer is between -1000 and 1000.
  • At most 50 lists are nested simultaneously, counting the outermost list.

More LinkedIn problems

drafts saved locally
public long depthSumInverse(String nestedList) {
    // Write your code here
}
nestedList"[2,[3,[4]],5]"
expected31
checking account