Depth-Weighted Sum
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
1 sits at weight 1, 2 at weight 2 and 3 at weight 3: 1 + 4 + 9 = 14.
Example 2
Both integers sit directly inside items, so each has weight 1 and the total is 9.
Constraints
itemsholds at most 100 integers and at most 50 lists in total- Lists are nested at most 10 levels deep
-100 <= value <= 100for every integer
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.