Fibonacci Number

Easy

Topics
MathDynamic ProgrammingRecursion

The Fibonacci numbers satisfy F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2) for n > 1. Given n, return F(n).

Example 1

001112
Index i holds F(i), each the sum of its two neighbours to the left. F(2) = 1.
Cell index is i, cell value is F(i).
Input:  n = 2
Output: 1

Example 2

0011122334
Input:  n = 4
Output: 3

Constraints

  • 0 <= n <= 30
Editorial — intuition, approach, complexity and pitfalls

Intuition

Naive recursion recomputes the same subproblems exponentially. Since F(n) depends only on the previous two values, iterate and keep just those two.

Approach

  1. Return n directly for F(0)=0 and F(1)=1.
  2. Otherwise roll two variables forward n-1 times.
  3. Return the second.

Walkthrough

n = 6
0, 1, 1, 2, 3, 5, 8  -> F(6) = 8

Complexity

  • Time — O(n): one loop.
  • Space — O(1): two rolling variables (vs. O(n) for memoized recursion).

Common Pitfalls

  • The base case is n < 2, not n <= 2. F(2) is 1 and gets computed by the loop; short-circuiting it returns 2.
  • Two variables are enough. The recursive form without memoisation is O(2^n) and recomputes F(5) dozens of times for F(30), which is the thing the problem exists to show.

Full Solution — all languages

class Solution:
    def fib(self, n):
        if n < 2:
            return n
        prev, cur = 0, 1
        for _ in range(2, n + 1):
            prev, cur = cur, prev + cur
        return cur
SensAI
Beta
Tap the mic to stop voice mode