Algorithms and Data Structures · Junior · Question 28 of 75

Why is this Fibonacci function slow for n = 40?

function fib(n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);
}

Explanation

fib(n - 1) and fib(n - 2) both recompute the same smaller values, so the call tree has about 2ⁿ nodes. Caching results (memoization) or a simple loop makes it O(n).

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 28

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz