Sub topic 15
Choosing the Right Approach
This chapter assumes you can read Python, write loops and functions, and read Big-O notation. It also assumes you have worked through the earlier chapters on the call stack, tail calls, explicit stacks, and memoization. Here those ideas come together into one decision: given a problem, a language, and an expected input size, should you write it recursively or iteratively?
Neither approach is always better. Any recursive algorithm can be rewritten as a loop, and any loop can be rewritten as recursion. The two versions compute the same answer. They differ in four practical ways:
- How closely the code matches the shape of the problem.
- How much memory the program uses, and where that memory lives.
- Whether the program can crash when the input is deep.
- How easy the code is to read, debug, and change.
The Four Questions to Ask
1. What shape is the problem?
Some problems are linear. You walk a sequence once, and each step depends only on the step before it. Summing a list, counting characters, and scanning for a maximum all fit this pattern. Each one maps directly onto a loop with a few state variables, and recursion adds nothing.
Other problems are hierarchical. Directory trees, parsed expressions, JSON documents, and divide-and-conquer algorithms such as merge sort and quicksort all contain smaller copies of themselves. In these cases the recursive version usually reads like the definition of the data. The iterative version needs an explicit stack, and that stack only re-implements what the call stack was already doing for you.
2. How deep can the recursion go?
Recursion depth is the length of the longest chain of calls that are active at the same time. What counts is depth, not the total number of calls.
- A balanced binary tree with a million nodes is about 20 levels deep, which is safe for recursion.
- A linked list with a million nodes is a million levels deep, which will overflow the stack in most languages.
- A degenerate tree (a "tree" where every node has one child) behaves like a linked list.
If your input comes from users, files, or the network, you usually cannot bound its depth. An attacker can send a JSON document nested 100,000 levels deep. Depth that is safe in tests can still crash in production.
3. What does the language guarantee?
Tail-call optimization (TCO) is the compiler or runtime reusing the current stack frame for a call in tail position. It turns tail recursion into constant-space iteration. Whether you can rely on it depends on the language.
| Language | Tail calls in practice | Default depth behavior |
|---|---|---|
| Scheme | Guaranteed by the standard | Tail recursion runs in constant space |
| Haskell, Erlang, Elixir | Tail calls do not grow the stack | Recursion is the normal way to loop |
| Scala | `@tailrec` makes the compiler check self-recursion and turn it into a loop | Other calls use the JVM stack |
| Kotlin | `tailrec` modifier for self-recursion | Other calls use the JVM stack |
| C, C++ | Optimizers often do it at higher optimization levels, with no guarantee | Fixed thread stack, typically 1–8 MB |
| Java, C# | Not guaranteed | `StackOverflowError` / process crash |
| JavaScript | The ES2015 standard requires it, but only Safari's engine implements it | `RangeError` in most engines |
| Python (CPython) | Never performed | `RecursionError` near 1000 frames by default |
4. Is there repeated work?
When a function makes more than one recursive call, check whether those calls overlap. Naive Fibonacci recomputes the same values an exponential number of times. That is a problem with repeated work, not with recursion itself. You can fix it in two ways. Memoization keeps the recursive shape and caches results, but it still uses stack depth proportional to n. A bottom-up loop removes both the repeated work and the stack depth. Choose memoization when the set of subproblems you actually need is sparse or hard to list in order. Choose bottom-up when every subproblem up to n will be needed anyway.
A Decision Flow
Worked Example: Flattening Nested Lists
Suppose you need to flatten arbitrarily nested Python lists. The data is hierarchical, so recursion is the natural first draft:
def flatten_recursive(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten_recursive(x))
else:
out.append(x)
return out
print(flatten_recursive([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]This version is clear and correct for typical input. Now run it through the four questions. The shape is hierarchical, so recursion fits. Nothing overlaps, so memoization does not apply. Python has no TCO, and the recursive call is not in tail position anyway. That leaves depth. If the lists come from an untrusted source, depth is unbounded, so this version can crash.
The iterative version keeps a stack of iterators. Each iterator remembers where you were in one level of the list, which is the same information a stack frame would hold:
def flatten_recursive(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten_recursive(x))
else:
out.append(x)
return out
def flatten_iterative(items):
out = []
stack = [iter(items)]
while stack:
for x in stack[-1]:
if isinstance(x, list):
stack.append(iter(x))
break
out.append(x)
else:
stack.pop()
return out
# Build a list nested 5000 levels deep: [4999, [4998, [ ... [0] ... ]]]
nested = [0]
for i in range(1, 5000):
nested = [i, nested]
print(flatten_iterative([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]
result = flatten_iterative(nested)
print(len(result), result[:3]) # 5000 [4999, 4998, 4997]
try:
flatten_recursive(nested)
except RecursionError:
print("flatten_recursive: RecursionError")The for ... else clause runs only when the inner loop finishes without break. That means the current level is exhausted, so it gets popped. When the loop finds a sublist, it pushes a new iterator and breaks, and the while loop resumes with the deeper level. The order of the output matches the recursive version.
The iterative version is longer and harder to read at a glance. You pay for that in readability and get safety in return. Whether the cost is worth it depends entirely on where your input comes from.
Common Mistakes When Choosing
- Converting everything to loops "for performance." In CPython a function call costs more than a loop iteration, but for a tree of depth 20 the difference rarely matters. Measure before you trade clarity for speed.
- Blaming recursion for exponential time. Naive Fibonacci is slow because of overlapping subproblems. A loop that does the same redundant work would be just as slow.
- Forgetting that the explicit stack also uses memory. An explicit stack moves memory from the call stack to the heap. Space is still O(depth). You gain a much larger limit and a clean failure mode (
MemoryError, or a check you write yourself), but not free space. - Assuming TCO from another language. A tail-recursive function written in a Scheme style will still overflow in Python, Java, and most JavaScript engines.
- Testing only shallow inputs. Add a test with the deepest input you expect, plus one far beyond it, so you find out how the code fails.
Summary of Criteria
| Situation | Recommended approach |
|---|---|
| Linear traversal, simple state | Loop |
| Hierarchical data, depth known to be small (balanced trees, divide and conquer) | Recursion |
| Hierarchical data, depth unbounded or user-controlled | Explicit stack |
| Tail-recursive logic in a language with guaranteed TCO | Tail recursion |
| Tail-recursive logic without TCO | Loop with parameters turned into variables |
| Overlapping subproblems, sparse or irregular | Memoized recursion |
| Overlapping subproblems, all needed in order | Bottom-up loop |
| Mutual recursion over deep input | State machine loop, or trampolining |
Exercise
A service parses arithmetic expressions submitted by users, such as "((1+2)*(3-4))". The parser is a recursive descent parser written in Java. Identify the risk and suggest two ways to reduce it.
Show answer
Nesting depth is controlled by the user, and Java does not guarantee tail-call optimization, so a deeply parenthesized input can throw StackOverflowError and might crash the request thread. One option is to enforce a maximum nesting depth (for example, 200) and reject deeper input with a clear error. That keeps the readable recursive parser. The other option is to rewrite the parser iteratively with an explicit operator and operand stack, such as the shunting-yard algorithm, so depth no longer uses the call stack.
Exercise
You need the number of ways to climb n stairs taking 1 or 2 steps at a time, for n up to 1,000,000, in Python. Which approach do you choose and why?
Show answer
Use a bottom-up loop. The recurrence ways(n) = ways(n-1) + ways(n-2) has overlapping subproblems, so naive recursion takes exponential time. Memoization fixes the time, but its recursion depth would be about n, far past CPython's limit of about 1000. A bottom-up loop that keeps only the last two values runs in O(n) time with O(1) extra space and has no depth limit.
Exercise
A colleague replaces a recursive in-order traversal of a balanced binary search tree containing 10 million keys with an explicit-stack version "to avoid stack overflow." Is the change justified?
Show answer
Probably not. A balanced tree with 10 million keys is only about 24 levels deep, well within any default stack limit. The explicit-stack version uses the same O(log n) space and is harder to read. The change would make sense only if the tree is not guaranteed to stay balanced, because a degenerate tree can be as deep as it has nodes.