Sub topic 15
Choosing the Right Approach
This chapter assumes you have read the earlier chapters on the call stack, depth limits, tail calls, explicit stacks, and memoization. It does not teach new techniques. It shows how to decide which form to write.
Three Questions to Ask
Most choices between recursion and iteration come down to three questions.
- What shape is the problem? If the data or the work is nested (trees, nested lists, grammars, divide-and-conquer), recursion usually matches it directly. If the work is a straight sequence of steps, a loop says the same thing more simply.
- How deep can the calls go? Recursion depth grows with the input. For a balanced tree, depth is about log n, which is safe. For a linked list or a degenerate tree, depth is n, and CPython stops at about 1000 frames by default.
- What does the language support? Scheme guarantees tail-call optimization. Many functional language compilers also perform it. Python, Java, and JavaScript in most engines do not. In those languages, tail recursion still uses one frame per call.
Comparing the Options
| Approach | Best fit | Extra space | Main risk |
|---|---|---|---|
| Loop | Linear sequences, counters | O(1) usually | Awkward for nested data |
| Plain recursion | Trees, divide-and-conquer | O(depth) call frames | Stack overflow on deep input |
| Tail recursion | Accumulator-style work in TCO languages | O(1) with TCO, O(n) without | Silent overflow where TCO is absent |
| Explicit stack | Deep or untrusted nested input | O(depth) on the heap | More code, harder to read |
| Memoization / bottom-up | Overlapping subproblems | O(n) cache or O(1) rolling state | Cache memory, cache key mistakes |
A Worked Choice
Summing a nested list of shallow depth fits recursion. Summing a flat list of a million numbers fits a loop.
def nested_sum(item):
if isinstance(item, list):
return sum(nested_sum(x) for x in item)
return item
print(nested_sum([1, [2, [3, 4]], 5])) # 15
data = list(range(1_000_000))
total = 0
for x in data:
total += x
print(total) # 499999500000A recursive version of the second task, such as first + rest_sum(rest), would need a million frames and raise RecursionError. If the nested input came from users and could be thousands of levels deep, you would switch nested_sum to an explicit stack.
Common Mistakes
- Assuming tail recursion is safe in Python. CPython never eliminates tail calls.
- Converting everything to loops. An iterative tree traversal with a manual stack is often harder to verify than the recursive one, and the gain is nothing when depth is about log n.
- Ignoring overlapping subproblems. Exponential time is usually a bigger problem than stack depth. Fix the repeated work first.
- Choosing by habit. Write the clearest version first, then check the worst-case depth against real input sizes.
Exercise
You need to process a parsed JSON document in Python. Most documents are nested a few levels deep, but the service accepts uploads from the public. Should you use plain recursion, tail recursion, or an explicit stack, and why?
Show answer
Use an explicit stack. The data is nested, so recursion fits its shape, but public input can be nested deeply enough to exceed CPython's recursion limit. Tail recursion would not help because CPython does not perform tail-call optimization.
Exercise
A recursive function computes the number of paths in a grid by calling itself on the cell to the right and the cell below. It is correct but slow for a 30 by 30 grid. What is the first fix to apply?
Show answer
Memoize it or rewrite it bottom-up. The calls overlap heavily, so the running time is exponential. Recursion depth is only about 60, so stack depth is not the problem.