Fibonacci Number

Pattern: Recursion basics

easy

The recursive definition of Fibonacci is easy to write and very slow to run. Keeping only the last two values turns it into one short loop.

The problem

The Fibonacci numbers start with F(0) = 0 and F(1) = 1, and every later one is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, ... You are given n from 0 to 30. Return F(n). For example, F(5) = 5 and F(10) = 55.

The function name fib matches LeetCode. Use the link above for the exact statement.

Think first

  • Write the definition as a recursive function. How many calls does it make for n = 5? Draw the tree of calls.
  • In that tree, how many times is F(2) computed?
  • To produce the next Fibonacci number, how many earlier numbers do you actually need to remember?

Hints

    Brute force, and why it fails

    The plain recursive version follows the definition exactly. For n = 30 it makes about 2.7 million calls, because every smaller value is recomputed again and again. That still runs within the limits here, but it doubles in cost roughly every two steps of n: n = 50 would take billions of calls.

    Storing each answer the first time it is computed (memoisation) fixes that and is the first step towards dynamic programming. Walking upwards with two variables fixes it too, and needs no extra memory.

    The key insight

    Recursion is not slow in itself; repeating work is. Fibonacci's recursion recomputes the same values, but every value only needs the two before it, so a loop that keeps the last two values does the job in n steps.

    Dry run

    00 
    11 
    previous0
    current1

    n = 5. F(0) = 0 and F(1) = 1 are known. previous holds F(0) and current holds F(1). The array lists the values found so far.

    Step 1 of 6

    The plan

    if n < 2:
        return n                      # F(0) = 0, F(1) = 1
    previous = 0                      # F(i - 2)
    current = 1                       # F(i - 1)
    for i from 2 to n:
        next = previous + current
        previous = current
        current = next
    return current
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One addition per step from 2 to n, and only two remembered values. The plain recursion, by comparison, takes about 1.6ⁿ calls and O(n) stack space.

    Edge cases

    • n = 0 returns 0 and n = 1 returns 1, straight from the first check.
    • n = 2 runs the loop once and returns 1.
    • F(30) = 832,040 fits easily in 32 bits. (F(47) would be the first to overflow, outside this problem's range.)
    I've built my logic, show the code

    Java

    class Solution {
        public int fib(int n) {
            if (n < 2) {
                return n;                   // F(0) = 0, F(1) = 1
            }
            int previous = 0;               // F(i - 2)
            int current = 1;                // F(i - 1)
            for (int i = 2; i <= n; i++) {
                int next = previous + current;
                previous = current;
                current = next;
            }
            return current;
        }
    }

    C++

    class Solution {
    public:
        int fib(int n) {
            if (n < 2) {
                return n;                   // F(0) = 0, F(1) = 1
            }
            int previous = 0;               // F(i - 2)
            int current = 1;                // F(i - 1)
            for (int i = 2; i <= n; i++) {
                int next = previous + current;
                previous = current;
                current = next;
            }
            return current;
        }
    };

    Python

    class Solution:
        def fib(self, n: int) -> int:
            if n < 2:
                return n                    # F(0) = 0, F(1) = 1
            previous, current = 0, 1        # F(i - 2), F(i - 1)
            for _ in range(2, n + 1):
                previous, current = current, previous + current
            return current

    Common mistakes

    • Using the plain recursion for larger n and running out of time.
    • Shifting in the wrong order (current = next before previous = current), which loses a value.
    • Returning previous instead of current at the end.
    • Forgetting n = 0, which should return 0, not 1.

    Similar problems