Nested List Weight Sum (for E4)
Problem statement
You are given a valid JSON string nestedList encoding a nested list of integers. Each list element is an integer or another list. Return the sum of every integer multiplied by the number of enclosing lists. Integers directly inside the outer list have depth 1.
For this exercise, use the JSON text as the portable input representation. Spaces may occur between tokens. Empty inner lists contribute zero. The outer list has between 1 and 50 elements, integer values are from -100 through 100, and integer depth is at most 50.
Function
depthSum(nestedList: String) → intExamples
Example 1
nestedList = "[[1,1],2,[1,1]]"return = 10Four 1s are at depth 2, and 2 is at depth 1. The weighted sum is 1 × 2 + 1 × 2 + 2 × 1 + 1 × 2 + 1 × 2 = 10.
Example 2
nestedList = "[1,[4,[6]]]"return = 27The value 1 is at depth 1, 4 is at depth 2, and 6 is at depth 3. The weighted sum is 1 × 1 + 4 × 2 + 6 × 3 = 27.
Example 3
nestedList = "[0]"return = 0The value 0 is at depth 1, so the weighted sum is 0 × 1 = 0.
Constraints
- The string is valid nested-list JSON containing only integer values, lists, commas, and optional spaces.
- The decoded outer list contains 1 through 50 elements.
- Every integer is in
[-100,100], and maximum integer depth is 50. - For this exercise, assume the JSON text has at most 100000 characters.