AlgoFrames

Memoized Fibonacci

Warm-up · Write code · about 8 min

Return the n-th Fibonacci number: fib(0) = 0, fib(1) = 1 and fib(n) = fib(n - 1) + fib(n - 2).

The plain recursive version makes billions of calls for n = 50. Add a memo so every n is computed once.

Example 1

Input:

[5]

Output:

5

0, 1, 1, 2, 3, 5: fib(5) is 5. With a memo it takes 9 calls.

Example 2

Input:

[10]

Output:

55

Constraints

  • 0 ≤ n ≤ 70
  • The answer fits exactly in a JavaScript number for every n in range

Learn the idea first: Overlapping subproblems and memoization, a visual lesson.

More Overlapping subproblems and memoization problems