LeetCode #509 Easy

Fibonacci Number

Fibonacci Number is LeetCode 509 (Easy). The sequence starts with F(0) = 0 and F(1) = 1, and every later term is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, … Given n, return F(n).

  • n is between 0 and 30, so the answer is at most F(30) = 832,040 and fits in a 32-bit int.
Constraints
  • 0 <= n <= 30
mathdynamic programmingrecursionmemoization
Open on LeetCode ↗
02

Intuition

To get the next term you only ever need the last two. So keep just a pair, prev = F(i − 1) and curr = F(i), and slide it one place to the right: the new pair is (curr, prev + curr). Starting from (F(0), F(1)) = (0, 1), after n − 1 slides curr holds F(n).

The definition written straight as recursion is correct but wasteful. fib(5) asks for fib(4) and fib(3), and fib(4) asks for fib(3) again. The repeats multiply at every level, so the number of calls grows about 1.6 times with each step of n. The loop computes each term exactly once.

How to spot this pattern

A sequence where each term depends on a fixed number of earlier terms. Keep only that many values and roll them forward, instead of a table or a recursion tree.

03

Approach

Try it first

Before reading on, count how many times plain recursion computes fib(2) while finding fib(6). Then write a loop that keeps only two numbers. Aim for O(n) time and O(1) space.

1

Return n when it is 0 or 1

F(0) = 0 and F(1) = 1, so return n covers both. The loop below starts from a ready-made pair, so these two cases must be answered before it.

2

Start the pair at F(0) and F(1)

Set prev, curr = 0, 1. The loop always keeps prev = F(i − 1) and curr = F(i), starting with i = 1.

3

Slide the pair n − 1 times

Each round sets prev, curr = curr, prev + curr, moving i up by one. Python evaluates the whole right side before assigning, so both new values use the old pair. In C++ and Java, store prev + curr in a temporary first.

4

Return curr

The pair started at i = 1 and moved n − 1 times, so i = n and curr is F(n).

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def fib(self, n: int) -> int:
▶3 if n < 2:
▶4 return n
▶5 prev, curr = 0, 1
▶6 for _ in range(n - 1):
▶7 prev, curr = curr, prev + curr
▶8 return curr
the sequence, F(0) to F(7)F(0)F(1)F(2)F(3)F(4)F(5)F(6)F(7)7n≥2n is 7 → it has to be built from F(0) and F(1)
n7
F(7) is not one of the two given terms, so the code moves on to the loop. The dashed slots are the terms the loop will pass through.
the sequence, F(0) to F(7)0F(0)prev1F(1)currF(2)F(3)F(4)F(5)F(6)F(7)0prev1currpair starts at F(0) = 0 and F(1) = 1
prev0
curr1
The pair holds the last two terms. These are the only two numbers the loop will ever keep; the earlier terms fade once the pair moves past them.
the sequence, F(0) to F(7)0F(0)1F(1)prev1F(2)currF(3)F(4)F(5)F(6)F(7)0old prev+1old curr=1new currslide 1: 0 + 1 = 1 → F(2)
prev1
curr1
F(2) = F(0) + F(1) = 0 + 1 = 1. The old curr, 1, becomes the new prev, so the pair moves one place right. Both new values are computed from the old pair at the same time.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)prev2F(3)currF(4)F(5)F(6)F(7)1old prev+1old curr=2new currslide 2: 1 + 1 = 2 → F(3)
prev1
curr2
F(3) = F(1) + F(2) = 1 + 1 = 2. The old curr, 1, becomes the new prev, so the pair moves one place right.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)2F(3)prev3F(4)currF(5)F(6)F(7)1old prev+2old curr=3new currslide 3: 1 + 2 = 3 → F(4)
prev2
curr3
F(4) = F(2) + F(3) = 1 + 2 = 3. The old curr, 2, becomes the new prev, so the pair moves one place right.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)2F(3)3F(4)prev5F(5)currF(6)F(7)2old prev+3old curr=5new currslide 4: 2 + 3 = 5 → F(5)
prev3
curr5
F(5) = F(3) + F(4) = 2 + 3 = 5. The old curr, 3, becomes the new prev, so the pair moves one place right.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)2F(3)3F(4)5F(5)prev8F(6)currF(7)3old prev+5old curr=8new currslide 5: 3 + 5 = 8 → F(6)
prev5
curr8
F(6) = F(4) + F(5) = 3 + 5 = 8. The old curr, 5, becomes the new prev, so the pair moves one place right.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)2F(3)3F(4)5F(5)8F(6)prev13F(7)curr5old prev+8old curr=13new currslide 6: 5 + 8 = 13 → F(7)
prev8
curr13
F(7) = F(5) + F(6) = 5 + 8 = 13. The old curr, 8, becomes the new prev, so the pair moves one place right.
the sequence, F(0) to F(7)0F(0)1F(1)1F(2)2F(3)3F(4)5F(5)8F(6)13F(7)answer13F(7)6 slides done → curr is F(7) = 13
answer13
The pair started at F(1) and moved 6 times, so curr now holds F(7). Each term was computed exactly once, with one addition.
05

Recursion with a memo

The recursive definition, with each value cached the first time it is computed. Every later request for the same k is answered from the cache, so only n + 1 distinct calls do real work.

▶1from functools import cache
▶2 
▶3 
▶4class Solution:
▶5 def fib(self, n: int) -> int:
▶6 @cache
▶7 def f(k: int) -> int:
▶8 if k < 2:
▶9 return k
▶10 return f(k - 1) + f(k - 2)
▶11 
▶12 return f(n)
06

Common pitfalls

Updating the pair one variable at a time

✗ Wrong
prev = curr
curr = prev + curr
✓ Right
prev, curr = curr, prev + curr

After the first line prev already equals curr, so the second line doubles curr instead of adding the old prev. The pair becomes 1, 2, 4, 8, … and n = 5 returns 16 instead of 5.

Sliding the pair one time too many

✗ Wrong
for _ in range(n):
✓ Right
for _ in range(n - 1):

The pair already starts at F(1), so only n − 1 slides are needed. One extra slide returns F(n + 1): n = 2 gives 2 instead of 1.

07

Complexity

Time
O(n)
Space
O(1)
The loop runs n − 1 times with one addition each, and only two numbers are kept. The memo version is also O(n) time but stores n + 1 values and recurses n deep.
08

Fibonacci Number FAQ

Why is plain recursion slow if n is only 30?

It still passes at 30, but fib(30) makes 2,692,537 calls to produce 31 different values. The call count is 2 · F(n + 1) − 1, so it grows like the sequence itself: n = 50 would need about 40 billion calls, while the loop needs 49 additions.

How do I print the Fibonacci series in Python?

Use the same pair, but print the smaller number before each slide. Start with a, b = 0, 1, then repeat print(a, end=" ") and a, b = b, a + b inside for _ in range(10). That prints the first 10 terms: 0 1 1 2 3 5 8 13 21 34.

Is there a faster way for very large n?

Yes. Raising the matrix [[1, 1], [1, 0]] to the power n by repeated squaring gives F(n) in O(log n) multiplications, and fast doubling does the same with plain formulas. Binet's closed formula uses floating point and stops being exact around n = 70. In a 32-bit int the largest term is F(46); F(47) already overflows.