Dynamic programming

O(n)·O(n) space
Whole table

Drag to pan; pinch or Ctrl+scroll to zoom, which stops at the whole table; arrow keys pan once the picture has focus. The headers stay put while you pan.

F(0), not yet filledF(1), not yet filledF(2), not yet filledF(3), not yet filledF(4), not yet filledF(5), not yet filledF(6), not yet filledF(7), not yet filledF(8), not yet filledF(9), not yet filledF(10), not yet filledF(0)0F(1)1F(2)2F(3)3F(4)4F(5)5F(6)6F(7)7F(8)8F(9)9F(10)10the tableFvalue→ i↓ F(i)

The table has 1 row and 11 columns, and nothing has been worked out yet. Every cell is the sum of the two before it, so the row can be filled left to right.

The table has 1 row and 11 columns, and nothing has been worked out yet. Every cell is the sum of the two before it, so the row can be filled left to right.
Answer so far—

F(i) = F(i−1) + F(i−2)

  1. 1write 0 and 1 into the first two cells; they are not computed from anything
  2. 2read the two cells behind the next one
  3. 3write their sum into it
  4. 4stop: the last cell holds F(n)
Cells filled
0
Cells read
0
Values written
0

Complexity

BestO(n)
AverageO(n)
WorstO(n)
Extra spaceO(n)
2n at n=11 predicts 22; this run took 0.

Fibonacci, bottom-up

Every Fibonacci number is the sum of the two before it, and that is a recurrence with two base cases: F(0) is 0 and F(1) is 1. Written as a recursion it recomputes the same subproblem an exponential number of times. Written as a table it does not: fill the two base cases, then walk left to right, and each cell needs only the two cells immediately behind it, which are already there by the time you reach it.

Its recurrence

F(i) = F(i−1) + F(i−2)

When it is the right choice

The technique, rather than this particular sequence, is what to take from this page: whenever a problem has a recurrence whose subproblems repeat, a table over those subproblems turns exponential work into linear work. Fibonacci itself is rarely the thing you actually need, which is why it is a good place to learn the shape — the recurrence is two terms wide and there is nowhere for the idea to hide behind the arithmetic.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n)
Worst
O(n)
Extra space
O(n)
Table
one dimension
Accepts
n from 1 to 20

The limits are pedagogical rather than technical: this tool keeps the whole table in every recorded step, so the shape of the table sets the size of the trace directly, and a run has to stay short enough to sit and watch. An input that would take more than three thousand steps on this algorithm is refused before a single step is generated, from a formula in the input sizes rather than by running it and finding out.

An unfilled cell is drawn differently from a cell holding a zero — no fill, a dashed outline, and no number at all — because early in a run that difference is most of the picture.

Worth comparing

All dynamic programming algorithms