Nested Depth Sum
mediumSave
Depth-First SearchRecursionStackString
Given a nested list of integers represented as a string, calculate the sum of all the integers weighted by their depth. The depth of an integer is the number of lists that directly or indirectly contain this integer.
For example, given the string [1,[4,[6]]], the function should compute the sum as 1*1 + 4*2 + 6*3.
Example 1
Input
[ "[1,[4,[6]]]" ]
Output
25
Explanation. Weighted sum calculation: 1*1 (depth 1) + 4*2 (depth 2) + 6*3 (depth 3) = 1 + 8 + 18 = 27.
Example 2
Input
[ "[1,2,3]" ]
Output
6
Explanation. All numbers are at depth 1: 1*1 + 2*1 + 3*1 = 6.
Example 3
Input
[ "[[[1]]]" ]
Output
3
Explanation. There is one number 1 at depth 3: 1*3 = 3.
Follow-up: Consider optimizing the solution for large inputs.
Constraints:
Each list may contain integers or other nested lists.
- Views
- 3