/339. Nested List Weighted Sum

339. Nested List Weighted Sum

Medium
Graphs85.9% acceptance

Given a nested list of integers, where each element is either an integer or a list, compute the sum of all integers in the list weighted by their depth. The depth of the top-level elements is 1. For example, an integer at depth 3 contributes its value multiplied by 3 to the sum. Implement a function that takes a nested list and returns the weighted sum.

Example 1

Input: [[2], 3, [4, [5]]]

Output: 2*2 + 3*1 + 4*2 + 5*3 = 4 + 3 + 8 + 15 = 30

Explanation: 2 at depth 2, 3 at depth 1, 4 at depth 2, 5 at depth 3

Example 2

Input: [1, [2, [3, [4]]]]

Output: 1*1 + 2*2 + 3*3 + 4*4 = 1 + 4 + 9 + 16 = 30

Explanation: 1 at depth 1, 2 at depth 2, 3 at depth 3, 4 at depth 4

Constraints

  • 1 <= length of nested_list <= 50
  • Each element is either an integer or a list
  • Integers are in the range -100 <= value <= 100
  • Maximum nesting depth is 50
Python (current runtime)

Case 1

Input: [5, [6, [7]]]

Expected: 5*1 + 6*2 + 7*3 = 5 + 12 + 21 = 38

Case 2

Input: [[[1]], 2]

Expected: 1*3 + 2*1 = 3 + 2 = 5

Case 3

Input: [[-1, [-2]], 3]

Expected: -1*1 + -2*2 + 3*1 = -1 + -4 + 3 = -2

Case 4

Input: [[], 10]

Expected: 10*1 = 10

Case 5

Input: [[[0]]]

Expected: 0*3 = 0