Skip to lesson

The cost of recursive code

How do you state the Big-O time and space complexity of a recursive method when the method calls itself? You write a recurrence relation T(n)—a one-line equation that says: "The cost for size n equals the cost of its recursive subcalls plus the local work done inside this call."

Recurrences in plain words

Let T(n) denote the work done by a recursive method on an input of size n. To write T(n), look at the method body and count two things:

  1. How many recursive calls does it make, and what size is passed to each call?

2.

Example 1 · Comparing T(n) = T(n - 1) + 1 vs T(n) = T(n - 1) + n

SteppingRecurrencesDemo.javaJava
public class SteppingRecurrencesDemo {    // T(n) = T(n - 1) + 1 -> O(n)    static int linear(int n) {        if (n <= 0) return 0;        return 1 + linear(n - 1);    }
    // T(n) = T(n - 1) + n -> O(n^2)    static int quadratic(int n) {        if (n <= 0) return 0;        int work = 0;        for (int i = 0; i < n; i++) work++;        return work + quadratic(n - 1);    }
    public static void main(String[] args) {        for (int n : new int[]{10, 100}) {            System.out.println("n=" + n + ": linear=" + linear(n) + ", quadratic=" + quadratic(n));        }    }}
Output
n=10: linear=10, quadratic=55
n=100: linear=100, quadratic=5050

What this code does

  • When n increases 10x (from 10 to 100), linear grows 10x (10 to 100), while quadratic grows ~100x (55 to 5050 = n(n+1)/2).
  • Both use O(n) stack space because both have recursion depth n.

How much non-recursive work (loops, comparisons, array copies) happens inside a single call? For example, in factorial(n), each call makes 1 recursive call of size n - 1 and does O(1) multiplication. In plain words: T(n) = T(n - 1) + 1. Unrolling n steps (1 + 1 + … + 1) gives T(n) = O(n). What if a recursive call contains a for loop of length n before calling f(n - 1)? Then T(n) = T(n - 1) + n, which unrolls to n + (n - 1) + … + 1 = (n(n+1))/2 = O(n²)!

  • T(n) = T(n - 1) + 1 ⇒ O(n) (e.g., factorial, recursive array sum).
  • T(n) = T(n - 1) + n ⇒ O(n²) (e.g., recursive selection sort, or slicing an array at each step).
  • T(n) = 2T(n - 1) + 1 ⇒ O(2ⁿ) (e.g., Tower of Hanoi, subset generation).

T(n) = T(n/2) + 1 and T(n) = 2T(n/2) + n

Now compare the four classic halving recurrences that appear in almost every interview.

Example 2 · Verifying the 4 halving recurrences empirically for n = 1024

FourHalvingRecurrencesDemo.javaJava
public class FourHalvingRecurrencesDemo {    // 1. T(n) = T(n/2) + 1 -> O(log n)    static int r1(int n) { return (n <= 1) ? 1 : 1 + r1(n / 2); }
    // 2. T(n) = 2T(n/2) + 1 -> O(n)    static int r2(int n) { return (n <= 1) ? 1 : 1 + 2 * r2(n / 2); }
    // 3. T(n) = 2T(n/2) + n -> O(n log n)    static int r3(int n) { return (n <= 1) ? 1 : n + 2 * r3(n / 2); }
    // 4. T(n) = T(n/2) + n -> O(n)    static int r4(int n) { return (n <= 1) ? 1 : n + r4(n / 2); }
    public static void main(String[] args) {        int n = 1024; // 2^10        System.out.println("T(n) = T(n/2) + 1  [O(log n)]   -> " + r1(n));        System.out.println("T(n) = 2T(n/2) + 1 [O(n)]       -> " + r2(n));        System.out.println("T(n) = 2T(n/2) + n [O(n log n)] -> " + r3(n));        System.out.println("T(n) = T(n/2) + n  [O(n)]       -> " + r4(n));    }}
Output
T(n) = T(n/2) + 1  [O(log n)]   -> 11
T(n) = 2T(n/2) + 1 [O(n)]       -> 2047
T(n) = 2T(n/2) + n [O(n log n)] -> 11264
T(n) = T(n/2) + n  [O(n)]       -> 2047

What this code does

  • For n = 1024 (log2(n) = 10): r1 is 10 + 1 = 11.
  • r2 is 2n - 1 = 2047; r3 is n * (log2(n) + 1) = 1024 * 11 = 11,264; r4 is 1024 + 512 + ... + 1 = 2047.

In detail:

  • T(n) = T(n/2) + 1 ⇒ O(log n) (1 call of n/2, O(1) work per level × log₂ n levels: Binary Search, Fast Power).
  • T(n) = 2T(n/2) + 1 ⇒ O(n) (2 calls of n/2, O(1) work per node × (2n - 1) nodes: Tree Traversal, Max by Halves).
  • T(n) = 2T(n/2) + n ⇒ O(n log n) (2 calls of n/2, O(n) work per level × log₂ n levels: Merge Sort).
  • T(n) = T(n/2) + n ⇒ O(n) (1 call of n/2, O(n) work at root + geometric series n + n/2 + n/4 + … = 2n: Quickselect).

Why does T(n) = 2T(n/2) + n equal O(n log n) while T(n) = T(n/2) + n equals O(n)?

  • In T(n) = 2T(n/2) + n (Merge Sort): level 0 does n work; level 1 has 2 calls of size n/2, totaling 2 · (n/2) = n work; level 2 has 4 calls of size n/4, totaling 4 · (n/4) = n work. Every one of the log₂ n + 1 levels does n work: n · (log₂ n + 1) = O(n log n)!
  • In T(n) = T(n/2) + n (Quickselect average case): there is only 1 call per level, so work shrinks geometrically: n + n/2 + n/4 + n/8 + … < 2n = O(n)!

Stack space

Total auxiliary space of a recursive method equals: Max Call-Stack Depth × Space per Frame + Shared Heap Allocations

Example 3 · How allocating an array before the recursive call multiplies space complexity

FrameSpaceCostDemo.javaJava
public class FrameSpaceCostDemo {    // Each of the n active frames holds an int[n] array simultaneously -> O(n^2) space!    public static int heavyFrames(int n, int currentLiveInts) {        if (n == 0) return currentLiveInts;        int[] localSlice = new int[n]; // stays alive in this frame while child runs!        return heavyFrames(n - 1, currentLiveInts + localSlice.length);    }
    public static void main(String[] args) {        System.out.println("Peak live ints for n=100: " + heavyFrames(100, 0));    }}
Output
Peak live ints for n=100: 5050

What this code does

  • Because localSlice is referenced in each stack frame while heavyFrames(n - 1) runs, all n arrays of sizes n, n-1, ..., 1 remain live simultaneously.
  • Total memory on the stack + heap is n(n+1)/2 = O(n^2) instead of O(n)!
  1. If each stack frame holds only a few primitive variables (O(1) space per frame), call-stack space is simply O(max recursion depth): O(n) for n - 1 recursions and O(log n) for n / 2 recursions.
  2. What if each call allocates a temporary array (like int[] temp = new int[hi - lo + 1] in Merge Sort)? Because merge runs after both child calls have returned and their temporary arrays are eligible for garbage collection, at most O(n) temporary array space is live at any instant (or O(n) if you allocate one shared aux buffer up front)!

Next step

Check your understanding

10 quick questions