Fibonacci Number

Easy Dynamic ProgrammingMath

Problem

Return the n-th Fibonacci number. F(0) = 0, F(1) = 1, F(n) = F(n−1) + F(n−2).

Example 1 Input: n = 2 Output: 1
Example 2 Input: n = 4 Output: 3
Example 3 Input: n = 10 Output: 55

Constraints

Approach — Dynamic Programming

This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) to O(n²) time.

Solution code

Python

class Solution:
    def fib(self, n):
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
        return a

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 c = a + b; a = b; b = c;
        }
        return b;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Fibonacci Number interactively → ← All solutions