Depth-Scaled Total of a Nested Integer Structure
Trees & GraphsAuto-graded · 21 test casesLast updated
Traverse an arbitrarily nested list of integers and add up each value multiplied by how deeply it is nested, testing DFS/BFS traversal of recursive structures.
Depth-Scaled Total of a Nested Integer Structure
You are given a list whose entries are each either an integer or another list of the same kind. Lists may be nested to any depth, and sublists may be empty.
The depth of an integer is the number of lists that enclose it. An integer sitting directly in the outermost list has depth 1, an integer in a list inside that list has depth 2, and so on.
Return the sum, over every integer in the structure, of value * depth.
For instance, in [1, [4, [6]]] the value 1 has depth 1, 4 has depth 2 and 6 has depth 3, so the result is 1*1 + 4*2 + 6*3 = 27.
Rules
- The outermost list is at depth 1.
- Empty lists contribute nothing to the total, no matter how deeply they are nested.
- Integers may be zero or negative; they are multiplied by their depth like any other value.
- If the input contains no integers (for example
[]or[[], [[]]]), the result is0.
Constraints
- The input is a list; every element is an integer or a list following the same rule.
- The total number of elements (integers plus sublists) is at most about 10^5.
- Nesting depth can be large, so a solution should not rely on very deep recursion.
- Integer values fit comfortably in Python's
int; the result is a single integer.
Examples
Example 1
Input: depth_scaled_total([1, [4, [6]]])
Output: 27
Example 2
Input: depth_scaled_total([[1, 1], 2])
Output: 6
Example 3
Input: depth_scaled_total([1, [4, [6]]])
Output: 27
Hints
Hint 1
The contribution of an integer depends only on its value and its depth, not on its neighbours, so any traversal that tracks depth works.
Hint 2
With DFS, carry the current depth along and add 1 each time you step into a sublist. To avoid recursion limits, keep an explicit stack of (list, depth) pairs.
Hint 3
With BFS, everything currently in the queue is at the same depth; increment the depth counter once after finishing each level.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each integer contributes value * depth, and that depends only on the integer itself and how many lists enclose it. So any traversal that visits every element exactly once while knowing the current depth will produce the answer.
The reference solution uses an iterative DFS with an explicit stack of (list, depth) pairs:
- Start with the outer list paired with depth 1.
- Pop a pair and scan its elements.
- If an element is an integer, add
element * depthto the total. - If it is a list, push it with
depth + 1. - Stop when the stack is empty.
An explicit stack avoids Python's recursion limit on very deep inputs.
Why it is correct
- Invariant: every pair
(items, d)on the stack holds a list whose direct elements are at depthd. This holds for the root (depth 1), and it is preserved because a sublist inside a depth-dlist is pushed withd + 1. - Each list is pushed once (by its parent, or initially for the root) and popped once, so each integer is visited exactly once at its true depth.
- Addition is commutative, so the order in which lists are processed does not matter.
- Empty lists are pushed and scanned but add nothing, so they have no effect on the total.
BFS alternative
Process level by level with a queue of lists: all lists in the queue share the same depth, so scan them, add value * depth for integers, enqueue sublists, then increment the depth after the level is done. The result is identical.
Complexity
- Time: O(N), where N is the total number of elements (integers and sublists), since each is examined once.
- Space: O(N) worst case for the stack in this iterative form (often closer to the nesting depth for narrow structures). A recursive DFS uses O(D) for depth D, and BFS uses O(W) for the maximum width W.
Reference solution
from typing import List
def depth_scaled_total(nested: List) -> int:
total = 0
stack = [(nested, 1)]
while stack:
items, depth = stack.pop()
for item in items:
if isinstance(item, int):
total += item * depth
else:
stack.append((item, depth + 1))
return total