Sum every number in an arbitrarily nested Python list with recursion and isinstance checks. O(n) over all elements, with deep-nesting tests.
The problem
nums contains integers and lists, nested to any depth. Return the sum of every integer.
[1, [2, 3], [4, [5, 6]]] → 21.
Examples
Example 1
Input
nested_sum([1, [2, 3], [4, [5, 6]]])
Expected output
21
Example 2
Input
nested_sum([1, 2, 3])
Expected output
6
+ 3 hidden tests on Submit.
Edge cases to ask about
- Empty lists
- Deep nesting
- Negative numbers
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Recursion on sublists | O(n) | O(d) | d = maximum nesting depth (stack frames). |
| bestExplicit stack | O(n) | O(n) | Avoids the recursion limit for very deep nesting. |
Walkthrough of the optimal approach (try it yourself first)
Loop over the items; numbers are added directly, lists are summed by a recursive call. Space is the nesting depth, not the element count.
An explicit stack of iterators is the non-recursive version and survives nesting deeper than the recursion limit.
Complexity: O(n) time, O(d) space. Every element and sublist is visited once; recursion depth equals the nesting depth d.
Reveal the reference solution
def nested_sum(nums): total = 0 for item in nums: if isinstance(item, list): total += nested_sum(item) else: total += item return total
Follow-ups interviewers ask
- Flatten it into a list instead.
- Weight each number by its depth.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Sum a Deeply Nested List Recursively in Python?
The optimal solution runs in O(n) time and O(d) auxiliary space. Every element and sublist is visited once; recursion depth equals the nesting depth d.
What is the brute-force approach, and how do you optimise it?
Recursion on sublists: O(n) time, O(d) space. d = maximum nesting depth (stack frames). Explicit stack: O(n) time, O(n) space. Avoids the recursion limit for very deep nesting.
What follow-up questions do interviewers ask about Sum a Deeply Nested List Recursively?
Flatten it into a list instead. Weight each number by its depth.
