Lesson 19 of 19
Dynamic programming with Fibonacci
Build a table of answers from left to right. Start with F(0) = 0 and F(1) = 1. Each later entry adds the two entries immediately before it.
Fill each Fibonacci cell once
A small answer can serve more than one later calculation. Store F(2) once and both F(3) and F(4) can read it. Filling the table in index order makes both inputs available before each addition.
Work through an example
A display requests Fibonacci entry 6. If entries 0 and 1 hold 0 and 1, what number should the display show?
Step-by-step solution
- Fill F(2) with 0 + 1 = 1. Then fill F(3) with 1 + 1 = 2.
- Read F(2) and F(3) to get F(4) = 1 + 2 = 3. Read F(3) and F(4) to get F(5) = 2 + 3 = 5.
- The two inputs for entry 6 are now in the table. F(6) = 3 + 5 = 8.
JavaScript example
const n = 6;
const table = [0, 1];
for (let i = 2; i <= n; i++) {
table[i] = table[i - 2] + table[i - 1];
}
table[n];DSA compiler
Try it yourself
Finish the animation to unlock this question.
Your table ends with F(3) = 2 and F(4) = 3. What belongs in the next cell?
Related exercise · Fibonacci sequence · Take the end-of-stage challenge