Imagine an array that contains both integers and nested arrays, such as the following:[8, 4, [5, [9], 3], 6].
The depth sum is described as the weighted sum of each integer, weighted by their respective depths. In the example, 8’s depth is 1, while 9’s is 3.
Given such an array, calculate its depth sum.
Examples
- Input:
[4, [5, 6]]
Output:4*1 + 2*5 + 2*6 = 26 - Input:
[8, 4, [5, [9], 3], 6]
Output:8*1 + 4*1 + 2*5 + 3*9 + 2*3 + 1*6 = 61
Summary (with approach)
Traverse the nested list with DFS/BFS carrying the current depth d.
- If it’s an integer:
sum += d * val; - If it’s a list: recurse/enqueue with
d+1.
Time O(N) over all elements; space O(H) for recursion/queue depth.
The VOprep team has long accompanied candidates through various major company OAs and VOs, including OpenAI, Google, Amazon, Citadel, SIG, providing real-time voice assistance, remote practice, and interview pacing reminders to help you stay smooth during critical moments. If you are preparing for Stripe or similar engineering-focused companies, you can check out our customized support plans—from coding interviews to system design, we offer full guidance to help you succeed.