Write factorial both recursively and iteratively (in words or pseudocode). Compare the two approaches, explain what happens on the call stack, and say when recursion is the better choice.
Show the explanation
Two versions
def fact_rec(n): # base case + recursive case
return 1 if n <= 1 else n * fact_rec(n - 1)
def fact_iter(n):
result = 1
for i in range(2, n + 1):
result *= i
return resultWhat recursion does on the call stack. Each call pushes a stack frame holding its parameters, local variables and return address. fact_rec(5) builds the frames 5 → 4 → 3 → 2 → 1. Then they unwind, multiplying on the way back. The extra space is O(n).
If the recursion is too deep, or has no reachable base case, the stack runs out:
- C/C++: a crash (segmentation fault), with a typical default stack of a few MB.
- Java:
StackOverflowError. - Python:
RecursionError. CPython's default limit is around 1000 frames, adjustable withsys.setrecursionlimit, which is risky.
Comparison
| Recursion | Iteration | |
|---|---|---|
| Clarity | natural for self-similar problems | natural for linear repetition |
| Memory | O(depth) stack | usually O(1) |
| Speed | call overhead for each step | usually a little faster |
| Risk | stack overflow on deep input | infinite loops |
When recursion is the better choice: problems whose structure is recursive. Tree and graph traversal (DFS), divide and conquer (merge sort, quicksort, binary search), backtracking (permutations, N-Queens, sudoku) and parsing nested expressions. The iterative versions need an explicit stack and are harder to read.
Making recursion safe and fast
- Memoisation turns exponential recursion, such as naive Fibonacci with O(2ⁿ) calls, into O(n). That is the top-down form of dynamic programming.
- Tail recursion: when the recursive call is the very last action, some compilers reuse the frame (tail-call optimisation). Scheme guarantees it. C/C++ compilers often do it at higher optimisation levels. Java and CPython do not, so deep tail recursion still overflows there.
- Any recursion can be converted into iteration with an explicit stack data structure.
Original UniCircle question. Last reviewed 22 Oct 2026.
