Sum of Nested Array

Medium~15 min

Given a nested array of integers, return the weighted sum of all integers. The weight of each integer is its depth in the nesting (1-indexed, where the top level is depth 1).

Multiply each integer by its depth, then return the total sum.

For example, given [1, [2, [3]]]:

  • 1 is at depth 1, contributing 1 * 1 = 1
  • 2 is at depth 2, contributing 2 * 2 = 4
  • 3 is at depth 3, contributing 3 * 3 = 9
  • Total = 1 + 4 + 9 = 14

You must solve this problem recursively.

Examples

Example 1
Input: nested = [1, [2, [3]]]
Output: 14
Explanation: 1*1 + 2*2 + 3*3 = 1 + 4 + 9 = 14. Each integer is multiplied by its nesting depth.
Example 2
Input: nested = [1, 2, 3]
Output: 6
Explanation: All at depth 1: 1*1 + 2*1 + 3*1 = 6.
Example 3
Input: nested = [[1, 1], 2, [1, 1]]
Output: 10
Explanation: The 1s are at depth 2 (4 * 1 * 2 = 8), the 2 is at depth 1 (2 * 1 = 2). Total = 8 + 2 = 10.

Constraints

  • The list can be nested to any depth
  • All leaf values are integers in the range -10^4 to 10^4
  • Total number of integers <= 10^3
  • Depth is 1-indexed (top level = 1)
  • You must use recursion
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run