Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 50 / 66

A smaller version of the question.

Solve a problem by reducing it, and prove there is a way to stop.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
IF input is the base case: return its answer
OTHERWISE solve one smaller input
COMBINE with the current value

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

recursion.py
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))
↳ EXPECTED OUTPUT
120
1
  1. 1

    The base case factorial(0) returns without another recursive call. The mathematical convention makes zero factorial one.

  2. 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. 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

TIME

O(n) calls in shown factorial

SPACE

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

A SMALL MISSION

Implement iterative factorial and compare it with the recursive result for 5.

Reveal one possible solution +
one_possible_solution.py
def factorial(number):
    result = 1
    for value in range(2, number + 1): result *= value
    return result
print(factorial(5))

06 Check your reasoning

QUICK SIGNAL CHECK

What must a recursive algorithm have?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.