Skip to content
Veltoryx Technologies
FreeProblem 65● EasyLeetCode #509 ↗4 min readUpdated 30 October 2026

Fibonacci Number

Compute the n-th Fibonacci number using top-down recursion with memoization to eliminate exponential duplicate calculations.

01The problem

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is:

  • F(0) = 0, F(1) = 1
  • F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

InputOutputWhy
n = 21F(2) = F(1) + F(0) = 1 + 0 = 1
n = 32F(3) = F(2) + F(1) = 1 + 1 = 2
n = 43F(4) = F(3) + F(2) = 2 + 1 = 3

Constraints: 0 <= n <= 30.

02How to spot it

  • The problem statement provides the exact recurrence relation: F(n) = F(n - 1) + F(n - 2).
  • Base cases are explicitly given: F(0) = 0, F(1) = 1.
  • A naive recursive tree recomputes identical values repeatedly (e.g. F(3) is computed multiple times when evaluating F(5)).
  • Adding a lookup cache (memoization) ensures each F(k) is evaluated only once.

So: recursion with memoization.

03Pseudocode

text
fib(n):
  if n <= 1: return n
  if n in memo: return memo[n]
  memo[n] = fib(n-1) + fib(n-2)
  return memo[n]
  1. Base cases: return 0 for 0 and 1 for 1.
  2. Check memo: if already computed, return the cached result.
  3. Compute fib(n-1) + fib(n-2), store in memo, and return it.

04Watch it work

Visualizer · step through the algorithmn = 5

current n

5

memo map

empty

status

start

Compute F(5) using top-down recursion with memoization.

Pseudocode

  1. fib(n):
  2. if n <= 1: return n
  3. if n in memo: return memo[n]
  4. memo[n] = fib(n-1) + fib(n-2)
  5. return memo[n]

Variables

n
5
step 1 / 15

05Step-by-step dry run

  1. 1

    current n

    5

    memo map

    empty

    status

    start

    Compute F(5) using top-down recursion with memoization.

    n = 5

  2. 2

    current n

    5

    memo map

    empty

    status

    calling F(4) and F(3)

    Computing F(5) = F(4) + F(3).

    k = 5

  3. 3

    current n

    4

    memo map

    empty

    status

    calling F(3) and F(2)

    Computing F(4) = F(3) + F(2).

    k = 4

  4. 4

    current n

    3

    memo map

    empty

    status

    calling F(2) and F(1)

    Computing F(3) = F(2) + F(1).

    k = 3

  5. 5

    current n

    2

    memo map

    empty

    status

    calling F(1) and F(0)

    Computing F(2) = F(1) + F(0).

    k = 2

  6. 6

    current n

    1

    memo map

    empty

    status

    base case F(1)=1

    Base case reached: F(1) = 1.

    k = 1result = 1

  7. 7

    current n

    0

    memo map

    empty

    status

    base case F(0)=0

    Base case reached: F(0) = 0.

    k = 0result = 0

  8. 8

    current n

    2

    memo map

    2 → 1

    status

    memo[2]=1

    Stored memo[2] = 1. Return 1.

    k = 2ans = 1

  9. 9

    current n

    1

    memo map

    2 → 1

    status

    base case F(1)=1

    Base case reached: F(1) = 1.

    k = 1result = 1

  10. 10

    current n

    3

    memo map

    2 → 13 → 2

    status

    memo[3]=2

    Stored memo[3] = 2. Return 2.

    k = 3ans = 2

  11. 11

    current n

    2

    memo map

    2 → 13 → 2

    status

    memo hit F(2)=1

    Memo hit! F(2) was already computed as 1. Return cached value.

    k = 2cached = 1

  12. 12

    current n

    4

    memo map

    2 → 13 → 24 → 3

    status

    memo[4]=3

    Stored memo[4] = 3. Return 3.

    k = 4ans = 3

  13. 13

    current n

    3

    memo map

    2 → 13 → 24 → 3

    status

    memo hit F(3)=2

    Memo hit! F(3) was already computed as 2. Return cached value.

    k = 3cached = 2

  14. 14

    current n

    5

    memo map

    2 → 13 → 24 → 35 → 5

    status

    memo[5]=5

    Stored memo[5] = 5. Return 5.

    k = 5ans = 5

  15. 15

    result F(n)

    5

    memo map

    2 → 13 → 24 → 35 → 5

    Completed: F(5) = 5.

    result = 5

06Java solution

FibonacciNumber.java
import java.util.HashMap;
import java.util.Map;

public class FibonacciNumber {
    private static final Map<Integer, Integer> memo = new HashMap<>();

    public static int fib(int n) {
        if (n <= 1) return n;
        if (memo.containsKey(n)) return memo.get(n);
        int ans = fib(n - 1) + fib(n - 2);
        memo.put(n, ans);
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(fib(2));
        System.out.println(fib(3));
        System.out.println(fib(4));
        System.out.println(fib(5));
    }
}
Expected output
1
2
3
5

07Why it works

Without memoization, the call tree branches in two at every step, creating O(2^n) total calls. By storing memo.put(n, ans) before returning, subsequent calls for the same value n take O(1) time. Because there are only n + 1 unique subproblems (F(0) through F(n)), the recursion tree collapses into a linear chain of n evaluations.

08Time and space

  • Time complexity: O(n). Each state from 0 to n is computed once.
  • Space complexity: O(n). The call stack reaches depth n, and the memo map stores n keys.

09Edge cases

  • n = 0: Immediately hits base case if (n <= 1) return n, returns 0.
  • n = 1: Immediately hits base case, returns 1.
  • n = 30 (constraint upper bound): Computes smoothly in milliseconds without integer overflow.

10Common mistakes

  • Omitting memoization. Running raw recursion takes O(2^30) ≈ 10^9 operations, which risks timing out or causing unnecessary CPU churn.
  • Using 0 as unvisited marker in a memo array. If using int[] memo, F(0) = 0 could be mistaken for an unvisited entry. Either initialize with -1 or use if (n <= 1) return n as a guard before array lookup.

11Other approaches

ApproachTimeSpaceNotes
Naive recursionO(2^n)O(n) stackToo slow, repeated work
Top-down memoizationO(n)O(n)Classic recursive lesson
Bottom-up DPO(n)O(1) spaceTwo variables a and b

12In the interview

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why does naive recursion for Fibonacci have O(2^n) time complexity?

  2. 2. How many distinct subproblems exist when computing F(n)?

14Solve it yourself

Try implementing the matrix exponentiation approach for Fibonacci:

  1. [[1, 1], [1, 0]]^n = [[F(n+1), F(n)], [F(n), F(n-1)]].
  2. Can you compute F(n) in O(log n) time using repeated squaring?