Skip to the content

Lesson 134 of 296

Recursion

What you will learn

  • What recursion is
  • Base case and recursive case
  • How the call stack runs a recursive function
  • Drawing a recursion tree
  • When recursion is slow, and how memoization fixes it
  • Recursion vs loops
On this page

What is recursion?

Recursion is when a function calls itself to solve a smaller version of the same problem. Many problems are naturally recursive: trees, nested data, combinations, divide and conquer.

Every recursive function needs two parts:

  1. Base case: the smallest problem, answered directly, with no recursive call. Without it, the function never stops.
  2. Recursive case: break the problem into a smaller one, call the function on it, and use the result.

Factorial

5! = 5 × 4 × 3 × 2 × 1 = 120. Notice 5! = 5 × 4!.

TypeScript
function factorial(n: number): number {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

How the call stack runs it

Each call waits for the call below it to return (Lesson 68):

factorial(4)
  4 * factorial(3)
        3 * factorial(2)
              2 * factorial(1)
                    returns 1          base case
              returns 2 * 1 = 2
        returns 3 * 2 = 6
  returns 4 * 6 = 24

The calls go down until the base case, then the answers come back up. The stack is 4 calls deep: O(n) space.

Stack overflow: in JavaScript, recursion a few thousand to tens of thousands of levels deep throws "Maximum call stack size exceeded". For very deep inputs, use a loop or an explicit stack (Lessons 81 and 136).

Three steps to write any recursive function

  1. Trust that the function already works for smaller inputs (this is called the "leap of faith").
  2. Write the base case for the smallest input.
  3. Write how to build the answer for n from the answer for a smaller input.

Sum of digits:

TypeScript
function sumDigits(n: number): number {
  if (n < 10) return n;
  return (n % 10) + sumDigits(Math.floor(n / 10));
}

Fast power: x^n in O(log n) by halving:

TypeScript
function power(x: number, n: number): number {
  if (n === 0) return 1;
  if (n < 0) return 1 / power(x, -n);
  const half = power(x, Math.floor(n / 2));
  return n % 2 === 0 ? half * half : half * half * x;
}

Recursion trees and repeated work

Naive Fibonacci (fib(n) = fib(n-1) + fib(n-2)):

TypeScript
function fibNaive(n: number): number {
  if (n < 2) return n;
  return fibNaive(n - 1) + fibNaive(n - 2);
}

Draw the calls as a tree:

                fib(5)
             /         \
        fib(4)          fib(3)
        /    \          /    \
    fib(3)  fib(2)  fib(2)  fib(1)
    ...

fib(3) is calculated twice, fib(2) three times, and so on. Each call makes two calls, so the time is about O(2ⁿ): fibNaive(50) would take hours.

Fix: remember results (memoization, Lesson 79), so each value is calculated once: O(n). This is the starting point of dynamic programming (Lesson 146).

TypeScript
function fibMemo(n: number, memo = new Map<number, number>()): number {
  if (n < 2) return n;
  const cached = memo.get(n);
  if (cached !== undefined) return cached;
  const result = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
  memo.set(n, result);
  return result;
}

Working out recursive complexity

  • Time ≈ number of calls × work per call. For a tree of calls: branches per call raised to the depth, roughly.
  • Space = maximum depth of the call stack (plus any data stored).
PatternTime
One call, input minus 1O(n)
One call, input halvedO(log n)
Two calls, input halved, O(n) work each level (merge sort)O(n log n)
Two calls, input minus 1 (naive Fibonacci)O(2ⁿ)

Recursion vs loops

Any recursion can be written with a loop and an explicit stack. Use recursion when it makes the code clearer (trees, backtracking, divide and conquer). Use loops for simple linear work and very deep inputs.

How to say it in an interview

"A recursive function solves a problem by calling itself on a smaller input and needs a base case to stop. Calls go down to the base case and results return up the call stack, so space is O(depth). I draw the recursion tree to estimate time: when it recomputes the same subproblems, like naive Fibonacci at O(2 to the n), I add memoization to get O(n). For very deep inputs I switch to iteration to avoid stack overflow."

Key words

WordMeaning
RecursionA function calling itself on a smaller problem
Base caseThe input answered directly, which stops recursion
Recursive caseThe step that calls the function again
Recursion treeA drawing of all the calls
Stack overflowToo many nested calls

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.