Recursion

O(n)·O(n) space
fib(10)n = 10
  • Running

Call fib(10).

Call fib(10).
  1. 1to find the nth Fibonacci number
  2. 2if n is 0 or 1, that is the answer already
  3. 3otherwise add the two before it together
  4. 4work out the (n-1)th the same way
  5. 5work out the (n-2)th the same way
  6. 6hand back their sum
Calls
1
Deepest stack
1
Additions
0
Reused from memo
0

Complexity

BestO(n)
AverageO(n)
WorstO(n)
Extra spaceO(n)
n at n=10 predicts 10; this run took 1.

Fibonacci, memoised

Memoised Fibonacci calls itself exactly the way naive Fibonacci does, but checks a memo table first: if fib(n) has already been worked out, it reads the remembered value back instead of recursing into it again. Once a value is remembered, it is set once and never recomputed.

When it is the right choice

This is the version worth using whenever the recursive structure itself is worth keeping, for readability or because the problem does not reduce cleanly to a loop. Memoisation turns the same exponential tree into one that visits each distinct subproblem once, at the cost of the memo table's O(n) space. An iterative version using two running variables would use O(1) space instead, and is the better choice when the recursive shape is not otherwise needed.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n)
Worst
O(n)
Extra space
O(n)
Largest input
n = 25

The largest input is a pedagogical ceiling rather than a technical one. This algorithm makes n calls, and past n = 25 the run stops being something a person can sit and watch — long before it reaches the step limit the tool enforces.

Worth comparing

All recursive algorithms