Recursion and Dynamic Programming
Factorial (Recursive)
factorial(0) = 1, otherwise factorial(n) = n * factorial(n - 1). The
smallest example of recursion with a single base case, used to visualise
the call stack growing on descent and shrinking on unwind.
Algorithm
Canonical input n = 5 gives factorial(5) = 120. The replay shows
six descent frames and five unwind frames (11 total).
Basic Implementation
basic.py
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
result = factorial(5)
print(result)
Complexity
- Time: O(n)
- Space: O(n) call stack
Implementation notes
- Python: no need to raise the recursion limit at this depth.
- The replay shows the call-stack contents on each frame and the
computed
n * factorial(n-1)value on each unwind, matching the lesson spec.
descend then unwind
Each non-base call awaits the result of the next call, then multiplies.