Basic Problemscountinglinearcombinatorics

Fibonacci Numbers

Return the nth Fibonacci number, where the sequence starts 0, 1 and each later term is the sum of the two before it. Naive recursion recomputes the same terms exponentially many times.

Do this lesson first: climbing stairs

Example input

n = 7

Expected output

13

Break it down

Answer each question out loud before you open it. Getting it wrong here is the useful part — a revealed answer you never guessed at teaches you nothing.

Fill the table

The table pauses before each cell you have to supply. Type the value the recurrence gives, and the write animation confirms it.

Step not started

Press start. The animation stops at every cell YOUR recurrence must fill.

dp[0] = 0 and dp[1] = 1 are given by definition; they cannot be derived. Every other cell depends only on smaller indices, so filling left to right guarantees both dependencies exist before they are read.

i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
0
1
1
2
3
5
8
13
21
fibonacci-numbers.ts
  1. 1function fib(n) {
  2. 2 const dp = [0, 1];
  3. 3 for (let i = 2; i <= n; i++) {
  4. 4 dp[i] = dp[i - 1] + dp[i - 2];
  5. 5 }
  6. 6 return dp[n];
  7. 7}
Given base caseYou computed it

The code, the trap, the variations

fibonacci-numbers.ts
  1. 1function fib(n) {
  2. 2 const dp = [0, 1];
  3. 3 for (let i = 2; i <= n; i++) {
  4. 4 dp[i] = dp[i - 1] + dp[i - 2];
  5. 5 }
  6. 6 return dp[n];
  7. 7}

Where people go wrong

Indexing off by one. Plenty of sources start the sequence 1, 1 rather than 0, 1, so dp[7] is 13 under one convention and 21 under the other. Fix the two base cases first and state them out loud before writing the loop.

  • Sum the two before it, but return the result modulo 1e9+7.

    The recurrence does not change at all. Only the combine step gains a modulo, which is why huge-n versions of this problem are still one line different.

  • Sum the three before it instead of the two.

    Three buckets instead of two, and a third base case. That is exactly Tribonacci — the state and the order are untouched.