Solvequill Blog · coding · 3 min read · 18 views

Naive fib(30) makes 2.7 million calls. Memoised, it makes 61.

Memoisation is not a speed trick bolted on afterwards. Counting the calls shows exactly which work it removes and why the shape of the recursion changes.

Published:

Loading the lesson…
The Solvequill lesson for this question.

The question

The naive recursive Fibonacci makes an enormous number of calls. Count exactly how many calls fib(n) makes, explain why memoisation reduces it to about 2n, and state the resulting complexity.

The left column multiplies by about 123 each time; the right adds 20.

What to notice first

Draw the call tree for fib(5) and the problem is visible immediately: fib(3) is computed twice, fib(2) three times, fib(1) five times. The recursion re-derives answers it already found, and the duplication compounds at every level.

Working it through

The naive version. Correct, and unusable past about :

Count the calls. Let C(n) be the total number of invocations. It satisfies its own recurrence, and solving it gives a closed form in terms of Fibonacci numbers themselves:

For so:

Since F(n) grows like , the call count grows exponentially — that is the real complexity, not O() as the two recursive calls might suggest:

Memoisation stores each result the first time it is computed, so every distinct argument is evaluated once:

There are only n distinct arguments, and each is computed once and then returned from the cache thereafter — about 2n+1 calls in total:

The answer

The cache holds n entries, so this buys O(n) time with O(n) space. An iterative version does the same in O(1) space by keeping only the last two values — memoisation is the general tool, not always the best one.

The mistake this one catches

Prefer to watch it? The lesson above walks through every line.

Turn your own question into an explanation video

Type the question or upload a photo; Solvequill produces a narrated video that walks through the solution step by step.

Open Solvequill

Keep reading