FunctionRacerProblemsRace

Depth-Weighted Sum

EasyRecursionPython, JavaScript, TypeScript

items is a list that mixes integers with inner lists, which may themselves hold integers and lists, to any depth. Every integer is weighted by how deep it sits: an integer directly inside items has weight 1, an integer inside a list that is directly inside items has weight 2, and so on, one more for each list it is wrapped in. Return the sum of every integer multiplied by its weight. Empty lists contribute nothing, so an empty items gives 0.

A stack of (list, depth) pairs works too, but a recursive helper that carries the current depth is the direct way.

For example, [1, [2, [3]]] gives 1 * 1 + 2 * 2 + 3 * 3 = 14.

Example 1

items [1,[2,[3]]]
returns 14

1 sits at weight 1, 2 at weight 2 and 3 at weight 3: 1 + 4 + 9 = 14.

Example 2

items [4,5]
returns 9

Both integers sit directly inside items, so each has weight 1 and the total is 9.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems