Recursion

Data Structures & Algorithms · First Steps · Intermediate · 12 min

A function that calls itself on a smaller version of the problem.

A stack of sticky notes on your desk. Every call writes a new note on top that says "waiting for the answer to a smaller question". When the smallest question is answered, you peel the notes off one by one, finishing each with the answer from the note above.

The idea in everyday words

Russian nesting dolls: to find the tiniest doll, open a doll, inside is a smaller doll, open that one too, until you reach a doll that doesn't open (the base case). Then you put them back together on the way out.

Two parts, always

  1. Base case – the tiniest problem you can answer directly (stops the recursion).
  2. Recursive case – shrink the problem and call yourself.

factorial(4) = 4 × factorial(3) = 4 × 3 × factorial(2) ... factorial(1) = 1

Trust the function

Don't try to trace every call in your head. Assume f(n-1) already works, then ask: how do I build f(n) from it? That's the "leap of faith".

Forgetting the base case = infinite calls = stack overflow.

Step by step

  1. fact(3):

    Not base → 3 × fact(2)

  2. fact(2):

    Not base → 2 × fact(1)

  3. fact(1):

    Base case → return 1

  4. Unwind:

    fact(2) = 2×1 = 2, fact(3) = 3×2 = 6

Code example

def factorial(n):
    if n <= 1:          # base case
        return 1
    return n * factorial(n - 1)

def countdown(n):
    if n == 0:
        print("Liftoff!")
        return
    print(n)
    countdown(n - 1)

print(factorial(5))
countdown(3)

Complexity

  • Time: O(n) for factorial(n); O(d) for digit_sum, where d = number of digits
  • Space: O(n) / O(d) for the call stack: every waiting call uses memory

Interview tips

  • Always state the base case first when explaining.

  • Recursion uses call-stack memory: mention it in space complexity.

  • Backtracking (permutations, subsets) = recursion + undo.

Challenge: Sum of Digits (recursively)

Return the sum of the digits of a non-negative integer using recursion.

Example: digit_sum(1234) → 10

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in First Steps

Previous: Big-O: How Fast Is My Code? · Next: Arrays, Memory & Dynamic Arrays