Fibonacci Number


Fibonacci Number – LeetCode


Problem: Fibonacci Number

Problem Statement

The Fibonacci numbers, commonly denoted F(n), form a sequence such that:

Given n, return the value of F(n).


Examples

Example 1
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1

Example 2
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2

Example 3
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3


Constraints


Intuition

The Fibonacci sequence is naturally recursive:
To compute F(n), we need the values of F(n - 1) and F(n - 2).

We can apply recursion directly and explain the flow using the Induction – Base Case – Hypothesis structure.


Induction – Base Case – Hypothesis Method

Function Signature

int fib(int n)

Base Case

These are the starting values of the Fibonacci sequence.

Hypothesis

Assume that the recursive calls fib(n - 1) and fib(n - 2) correctly return the (n - 1)th and (n - 2)th Fibonacci numbers.

Induction

Then, by the definition of the Fibonacci sequence, we can return:

fib(n) = fib(n - 1) + fib(n - 2)

Code (Java)

class Solution {
    public int fib(int n) {
        // Base Case
        if (n == 0) return 0;
        if (n == 1) return 1;

        // Hypothesis and Induction
        int first = fib(n - 1);
        int second = fib(n - 2);
        return first + second;
    }
}

Time and Space Complexity

Note: For large n, this recursive approach is inefficient. Use memoization or iterative DP for optimization.


Dry Run

Input: n = 4

Call stack:


Conclusion

The Fibonacci problem is one of the most fundamental recursion exercises. It clearly demonstrates the Induction – Base – Hypothesis reasoning in recursive function design. While the naive solution has exponential time, it lays the groundwork for optimized techniques like memoization and DP.