Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Big-O and Complexity

    Complexity of Recursion

    A recursive function calls itself on a smaller input (fully taught in 11recursion.md).

    Chapter 8 of 116 min read

    The Plain Picture#

    A chain message: "Send this to 2 friends." Each friend sends it to 2 more. After 10 rounds, 2¹⁰ = 1,024 people have it; after 30 rounds, over a billion. A tiny rule, repeated, explodes.

    The Real Names#

    • A recursive function calls itself on a smaller input (fully taught in Recursion).

    • Its running time is found by drawing a recursion tree: each call is a node, and its children are the calls it makes. Total time = (number of calls) × (work per call).

    • A recurrence relation writes this as a formula, e.g. T(n) = 2·T(n/2) + O(n).

    Under the Hood#

    The exponential blow-up — naïve Fibonacci#

    The Fibonacci numbers: 0, 1, 1, 2, 3, 5, 8, 13, … each is the sum of the previous two.

    Java
    static long fib(int n) {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2); // two calls per call
    }
                          fib(5)
                   ┌────────┴────────┐
                fib(4)             fib(3)
              ┌───┴───┐           ┌──┴──┐
           fib(3)   fib(2)     fib(2)  fib(1)
           ┌─┴─┐    ┌─┴─┐      ┌─┴─┐
        fib(2) f(1) f(1) f(0)  f(1) f(0)
        ┌─┴─┐
      f(1) f(0)
                      fib(3) is computed twice, fib(2) three times...

    Each call makes two more, so the number of calls roughly doubles (more precisely, grows by ×1.618) each time n increases by 1 — O(2ⁿ). Measured:

    Output
    fib(20) = 6765      calls = 21,891       time =  0.2 ms
    fib(25) = 75025     calls = 242,785      time =  0.5 ms
    fib(30) = 832040    calls = 2,692,537    time =  5.5 ms
    fib(35) = 9227465   calls = 29,860,703   time = 41.8 ms

    Every +5 to n multiplies the calls by about 11. fib(50) would need about 40 billion calls.

    The fix — remember answers you've already computed (memoization, the doorway to dynamic programming, Dynamic Programming I (coming soon)):

    Java
    static long fibMemo(int n, long[] memo) {
        if (n <= 1) return n;
        if (memo[n] != 0) return memo[n]; // already known → O(1)
        return (memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo));
    }
    // fibMemo(90) = 2880067194370816120  time = 0.009 ms

    Each value from 0 to n is now computed once: O(n) time, O(n) space. From "40 billion calls" to 90.

    Divide and conquer — the n log n shape#

    Merge sort (Sorting (coming soon)) splits the array in half, sorts each half recursively, and merges the halves in O(n): T(n) = 2·T(n/2) + O(n).

      level 0:          [ n ]                         work n
      level 1:      [ n/2 ][ n/2 ]                    work n     (2 pieces × n/2)
      level 2:  [n/4][n/4][n/4][n/4]                  work n
       ...                                            ...
      level log n:  [1][1][1] ... [1]                 work n
                                                      ─────────────
                                 log n levels × n per level = O(n log n)

    Common recurrences — the cheat table#

    RecurrenceMeaningResultExample
    T(n) = T(n/2) + O(1)halve, constant workO(log n)binary search
    T(n) = T(n−1) + O(1)shrink by 1, constant workO(n)recursive sum of a list
    T(n) = T(n−1) + O(n)shrink by 1, linear workO(n²)selection sort, recursively
    T(n) = 2T(n/2) + O(n)split in two, linear mergeO(n log n)merge sort
    T(n) = 2T(n/2) + O(1)split in two, constant workO(n)visiting every node of a balanced tree
    T(n) = 2T(n−1) + O(1)two calls, shrink by 1O(2ⁿ)naïve Fibonacci, all subsets
    n choices, then n−1, …try every orderO(n!)all permutations

    (A general formula for the "split into pieces" shapes is called the Master Theorem. For interviews, knowing this table is enough.)

    Branching rule of thumb: a recursion with b branches per call and depth d makes about bᵈ calls.

    Check yourself

    4 questions
    1

    Why is naïve fib O(2ⁿ)?

    Show answer

    Each call makes two more calls, so the call count roughly doubles as n grows by 1 (many subproblems are recomputed).

    2

    What does memoization change, and what's the new complexity?

    Show answer

    Each subproblem is computed once and then looked up: O(n) time, O(n) space.

    3

    Why is merge sort O(n log n)?

    Show answer

    There are log n levels of halving, and each level does O(n) total merging work.

    4

    A backtracking function tries 3 choices at each of n levels. Roughly how many calls?

    Show answer

    About 3ⁿ.