KatInterview

Depth-Scaled Total of a Nested Integer Structure

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsdfsbfsnested-lists

Last 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 is 0.

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.