Module 1 · Beginner · DSA foundations and complexity

Recursion explained, with Python examples

Recursion explained for beginners: base case, recursive case, the call stack, factorial, Fibonacci, recursion vs loops and the Big-O of recursive code.

By theprogrammers team · · 6 min read

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. It sounds like a trick, but it's one of the most important ideas in DSA: trees, graphs, merge sort, backtracking and dynamic programming are all built on it.

This lesson explains recursion step by step: the two parts every recursive function needs, what happens in memory when it runs, classic examples, how to work out its Big-O, and when to use a loop instead.

An everyday example

You're in a long queue and want to know your position, but you can't see the front. So you ask the person ahead: "what's your position?" They ask the person ahead of them, and so on, until the person at the very front says "1". Then each answer comes back down the queue, with each person adding 1.

That's recursion:

  • The recursive case: "my position is the position of the person ahead, plus 1".
  • The base case: the person at the front knows the answer without asking anyone: 1.

The two parts of every recursive function

Here's a countdown written recursively:

def countdown(n):
    if n == 0:              # base case: stop here
        print("Go!")
        return
    print(n)
    countdown(n - 1)        # recursive case: a smaller problem

countdown(3)
3
2
1
Go!
  1. The base case stops the recursion. Without it, the function calls itself forever.
  2. The recursive case calls the function on a smaller input, so each call gets closer to the base case.

If either is missing or wrong, you get Python's RecursionError: maximum recursion depth exceeded, the recursive version of an infinite loop.

Factorial: the classic example

The factorial of n, written n!, is n × (n − 1) × … × 1. So 5! = 5 × 4 × 3 × 2 × 1 = 120. Notice that 5! = 5 × 4!. A problem defined in terms of a smaller version of itself is perfect for recursion:

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

print(factorial(5))    # 120

What happens in memory: the call stack

Each function call gets its own small workspace, called a stack frame, holding its variables. Frames pile up on the call stack as calls are made, and come off as each one returns. For factorial(4):

factorial(4) waits for factorial(3)
  factorial(3) waits for factorial(2)
    factorial(2) waits for factorial(1)
      factorial(1) returns 1            <- base case
    factorial(2) returns 2 * 1 = 2
  factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24

The calls go down until they hit the base case, then the answers come back up. Every waiting call uses memory, which is why recursion depth matters: Python allows about 1,000 frames by default, so factorial(5000) fails with a RecursionError.

Recursion on lists and strings

A list can be split into "the first item" and "the rest", and the rest is a smaller list. That gives simple recursive solutions:

def total(nums):
    if not nums:                         # empty list
        return 0
    return nums[0] + total(nums[1:])     # first + sum of the rest

def reverse(text):
    if len(text) <= 1:
        return text
    return reverse(text[1:]) + text[0]

print(total([3, 1, 4, 1, 5]))    # 14
print(reverse("kanpur"))         # rupnak

(Slicing copies the list each time, so these are slower than a loop. They're here to show the idea.)

Fibonacci, and why naive recursion can be slow

Each Fibonacci number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13… The recursive version is a direct translation of the definition:

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(10))    # 55

It's correct, but painfully slow for big n. fib(5) calls fib(4) and fib(3); fib(4) calls fib(3) again, and so on. The same values are calculated over and over, and the number of calls roughly doubles with each step of n: O(2ⁿ). fib(35) makes about 30 million calls.

The fix is to remember answers you've already worked out, called memoisation. Python has it built in:

from functools import cache

@cache
def fast_fib(n):
    if n < 2:
        return n
    return fast_fib(n - 1) + fast_fib(n - 2)

print(fast_fib(100))    # 354224848179261915075

Each value is now computed once, so it's O(n). This idea, recursion plus remembering, is the heart of dynamic programming.

The Big-O of recursive code

Ask two questions:

  1. How many calls are made in total?
  2. How much work does each call do (not counting its own recursive calls)?

Multiply them for the time complexity.

FunctionCallsWork per callTimeSpace (stack depth)
factorial(n)nO(1)O(n)O(n)
fib(n), naiveabout 2ⁿO(1)O(2ⁿ)O(n)
fast_fib(n)nO(1)O(n)O(n)
Binary search, recursivelog nO(1)O(log n)O(log n)

Don't forget space: the call stack is as deep as the longest chain of waiting calls. See Big-O notation in Python for the basics.

Recursion or a loop?

Anything recursive can be written with a loop, and vice versa. Factorial with a loop:

def factorial_loop(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result
Use recursion whenUse a loop when
The data is naturally nested: trees, folders, JSONYou're processing items one after another
The problem splits into smaller copies: merge sortThe recursion would go very deep (thousands of levels)
You're exploring choices: backtrackingSpeed and memory matter most

In Python, prefer a loop for simple repetition. Use recursion where it makes the code much clearer, which you'll see with trees and backtracking.

How to write a recursive function

  1. Find the smallest input you can answer directly. That's the base case: an empty list, 0, a single character.
  2. Assume the function already works for a smaller input. This "leap of faith" is the key mental step.
  3. Use that smaller answer to build the answer for the full input.
  4. Check that every call gets smaller, so the base case is always reached.

Practice

  1. Write a recursive function power(x, n) that returns x to the power n, for n ≥ 0.
Show the answer
def power(x, n):
    if n == 0:
        return 1
    return x * power(x, n - 1)

print(power(2, 10))    # 1024

O(n) time. Can you make it O(log n) using x^n = (x^(n/2))²?

  1. Write a recursive function that counts the digits of a positive integer.
Show the answer
def count_digits(n):
    if n < 10:
        return 1
    return 1 + count_digits(n // 10)

print(count_digits(208001))    # 6
  1. Write a recursive function is_palindrome(s).
Show the answer
def is_palindrome(s):
    if len(s) <= 1:
        return True
    return s[0] == s[-1] and is_palindrome(s[1:-1])

print(is_palindrome("level"))    # True

Compare the outer characters, then check the inside.

Interview questions

What is recursion, and what are its two essential parts?

A technique where a function calls itself on a smaller subproblem. It needs a base case that returns without recursing, and a recursive case that moves towards the base case.

What causes a stack overflow in recursion?

Each call adds a frame to the call stack. Missing or unreachable base cases, or very deep recursion, exhaust the stack; Python raises RecursionError at about 1,000 levels by default.

Why is naive recursive Fibonacci O(2ⁿ), and how do you fix it?

Each call makes two more calls, and the same subproblems are recomputed many times, so the call tree grows exponentially. Memoisation (caching results) or an iterative version computes each value once, giving O(n).

Is recursion faster than iteration?

Usually not. Function calls have overhead and use stack memory; Python doesn't optimise tail calls. Recursion is chosen for clarity on naturally recursive problems, not speed.

What to learn next

  1. Learn a repeatable method for any problem in how to solve coding problems.
  2. Revisit Big-O notation and work out the complexity of each function above.