Dynamic programming · Exercise 70 of 100

Fibonacci sequence

Start with 0 at index 0 and 1 at index 1. Each later number is the sum of the two before it, so you only need to remember the latest pair. After adding them, keep the newer number and the sum as your next pair.

Try it yourself

A Fibonacci table begins with 0 at index 0 and 1 at index 1. What number goes at index 7?

One-step hint

Label the table columns from index 0 through index 7 before filling them. Under each new index, add the values in the two preceding columns.

Worked solution
  1. Add neighboring values to fill indices 2, 3, and 4 with 1, 2, and 3.
  2. The next two sums are 2 + 3 = 5 and 3 + 5 = 8, so index 7 holds 5 + 8 = 13.
DSA compiler

Explore the idea visually in the dynamic programming with fibonacci lab.