Browse curriculum

Fibonacci Number (LeetCode 509)

Compute the nth Fibonacci number bottom-up in O(n) time and O(1) space by keeping only the last two values, instead of exponential recursion.

Problem Understanding

Fibonacci Number: F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2) for n > 1. Given n, return F(n).

Example: n = 4 returns 3: the sequence is 0, 1, 1, 2, 3.

The Intuition: Compute Each Value Once

Fibonacci is the textbook entry to dynamic programming.

  1. Plain recursion follows the definition directly, but fib(n − 1) and fib(n − 2) both recompute fib(n − 3), and so on: exponential time.
  2. Memoization or a table computes each F(i) once: O(n).
  3. Two variables are enough, because F(i) only looks back two steps: O(1) space.

The same "previous two values" recurrence drives Climbing Stairs, Min Cost Climbing Stairs and House Robber.

Fibonacci Number Visualization

a = F(0), b = F(1)

F(i), index below

a

0

0

b

1

1

a

0

b

1

Answer

:

 

Start with a = F(0) = 0 and b = F(1) = 1

Next

F(2) = F(1) + F(0) = 1 + 0 = 1. Slide: a = 1, b = 1

Free preview: the first 3 of 7 steps

n

The values F(0) to F(n) fill left to right. Only a and b are kept; older values grey out because the two-variable solution no longer needs them. Try n = 20 to see 6765 reached in 19 additions.

Fibonacci Number Dry Run

Input: n = 6

i a (F(i−2)) b (F(i−1)) F(i) = a + b
2 0 1 1
3 1 1 2
4 1 2 3
5 2 3 5
6 3 5 8

Answer: 8.

Fibonacci Number LeetCode Solution

Bottom-up with two variables.

Fibonacci Number Code
1var fib = function(n) {
2 if (n < 2) return n;
3 let a = 0, b = 1;
4 for (let i = 2; i <= n; i++) {
5 [a, b] = [b, a + b];
6 }
7 return b;
8};

Fibonacci Number in Python, Java, C++, TypeScript and C

Fibonacci Number in Python
class Solution:
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        a, b = 0, 1
        for _ in range(2, n + 1):
            a, b = b, a + b
        return b
Fibonacci Number in Java
class Solution {
    public int fib(int n) {
        if (n < 2) return n;
        int a = 0, b = 1;
        for (int i = 2; i <= n; i++) {
            int next = a + b;
            a = b;
            b = next;
        }
        return b;
    }
}
Fibonacci Number in C++
class Solution {
public:
    int fib(int n) {
        if (n < 2) return n;
        int a = 0, b = 1;
        for (int i = 2; i <= n; i++) {
            int next = a + b;
            a = b;
            b = next;
        }
        return b;
    }
};
Fibonacci Number in TypeScript
function fib(n: number): number {
    if (n < 2) return n;
    let a = 0, b = 1;
    for (let i = 2; i <= n; i++) {
        [a, b] = [b, a + b];
    }
    return b;
}
Fibonacci Number in C
int fib(int n) {
    if (n < 2) return n;
    int a = 0, b = 1;
    for (int i = 2; i <= n; i++) {
        int next = a + b;
        a = b;
        b = next;
    }
    return b;
}

Edge Cases & Common Mistakes

  • n = 0 and n = 1: return n directly; the loop never runs.
  • Updating a before using it: a = b; b = a + b doubles b; use a temporary or a simultaneous assignment.
  • Plain recursion in an interview: correct but exponential; mention memoization or the iterative version.
  • Overflow: LeetCode limits n to 30, but F(47) already overflows a 32-bit int.
  • Matrix power: F(n) can be computed in O(log n) with fast exponentiation of [[1, 1], [1, 0]], useful for very large n.

Summary

Return n for the base cases. Otherwise keep a = F(i − 2) and b = F(i − 1), and replace them with (b, a + b) until reaching n. Each value is computed once: O(n) time and O(1) space, instead of exponential recursion.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Handle the base cases

    If n is 0 or 1, return n.

  2. Start the pair

    Set a = 0 (F(0)) and b = 1 (F(1)).

  3. Slide forward n − 1 times

    Replace (a, b) with (b, a + b). After the loop, b is F(n).

Frequently asked questions

Why is recursive Fibonacci slow?

fib(n) calls fib(n − 1) and fib(n − 2), and each of those calls two more, so the same values are recomputed again and again. The number of calls grows roughly like 1.6^n: fib(20) makes over 20,000 calls, while only 21 distinct values exist.


How does dynamic programming fix Fibonacci?

Compute each value once. Memoization caches fib(i) the first time it is computed (top-down); tabulation fills F(0), F(1), F(2), … in order (bottom-up). Both are O(n) time.


How do you get Fibonacci in O(1) space?

Each value only needs the previous two, so keep two variables a = F(i − 2) and b = F(i − 1). Each step computes a + b and slides the pair forward. No table is needed.

New to the technique behind this problem? Watch it run step by step:

Dynamic Programming Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description