Skip to content
StackDecode
Dynamic programmingAnimated

Fibonacci DP

Each number is the sum of the previous two; remember them instead of recomputing.

Time

O(n)

Extra space

O(1)

Use it for

The classic intro to memoisation.

How it works

  1. The plain recursive definition F(n) = F(n−1) + F(n−2) recomputes the same values exponentially many times.
  2. Instead store each answer in a table the first time it is computed (memoisation / tabulation).
  3. Fill the table from the bottom up: each entry needs only the two before it.
  4. O(n) time instead of exponential.

Watch it run

Loading animation…