Fibonacci Series
Recursion
๐ Problem Statement
Write a recursive function fib(n) that returns the -th Fibonacci number. The sequence is: for . Input: 6 โ Output: 8. Input: 7 โ Output: 13.
๐ก Intuition
Fibonacci has a natural recursive structure: each value depends on the two preceding it. The naive recursive solution mirrors the mathematical definition, but creates a binary tree of calls with many overlapping subproblems (e.g., is computed multiple times for ).
๐ง Approach
- Base cases: if , return 0. If , return 1.
- Recursive case: return .
- Each call branches into two sub-calls, creating a binary recursion tree.
โก Complexity Analysis
Time
โ exponential, because each call generates two new calls. Very slow for .
Space
โ the maximum depth of the recursion tree is
โ ๏ธ Common Mistakes
- Not having two base cases (both and are needed)
- Assuming this approach is efficient โ it is and should be memoized for real use
- Off-by-one errors in sequence indexing ( with 0-indexing)
- Confusing Fibonacci with factorial โ similar structure, different operations
๐ฏ Final Thoughts
Naive recursive Fibonacci is intentionally slow. Its purpose is to show how recursion can cause redundant work. This sets the stage for memoization, which reduces complexity to , and dynamic programming.