A smaller version of the question.
Solve a problem by reducing it, and prove there is a way to stop.
01 Model the idea
A recursive function calls itself on a smaller problem. It needs a base case and a progress argument: each call must move toward a terminating condition. The call stack stores unfinished work, so recursion has a space cost and a practical depth limit in Python. Iterative code is often simpler for flat repetition.
Each call makes measurable progress toward a valid base case.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
IF input is the base case: return its answer
OTHERWISE solve one smaller input
COMBINE with the current value03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def factorial(number):
if number < 0:
raise ValueError("number must be nonnegative")
if number == 0:
return 1
return number * factorial(number - 1)
print(factorial(5))
print(factorial(0))120 1
- 1
The base case factorial(0) returns without another recursive call. The mathematical convention makes zero factorial one.
- 2
Each positive call reduces its input by one, leaving a multiplication waiting on the stack. Time and stack space are linear in the input in this implementation.
- 3
For deep input, a loop avoids recursion-depth limits. Increasing the recursion limit is not a general fix for an algorithm that consumes excessive stack space.
04 Count the cost
O(n) calls in shown factorial
O(n) call stack
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Implement iterative factorial and compare it with the recursive result for 5.
Reveal one possible solution +
def factorial(number):
result = 1
for value in range(2, number + 1): result *= value
return result
print(factorial(5))06 Check your reasoning
What must a recursive algorithm have?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.