#509

Fibonacci Number

Easy Recursion → iteration

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the n-th Fibonacci number, where F(0) = 0, F(1) = 1 and each next number is the sum of the two before it.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: F(n) = F(n-1) + F(n-2), starting from 0 and 1.

Why this works: the recursion explains the idea, but it repeats work. Each value only needs the two before it, so roll two variables forward.

Example: n = 5

0, 1 → 1 → 2 → 3 → 5F(5) = 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Missing a base case — the recursion never stops (StackOverflowError).

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon