Algorithm LogbookAlgorithm Logbook

Fibonacci Series

Recursion

๐Ÿ“‹ Problem Statement

Write a recursive function fib(n) that returns the nn-th Fibonacci number. The sequence is: F(0)=0,โ€…โ€ŠF(1)=1,โ€…โ€ŠF(n)=F(nโˆ’1)+F(nโˆ’2)F(0) = 0,\; F(1) = 1,\; F(n) = F(n-1) + F(n-2) for n>1n > 1. 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., F(3)F(3) is computed multiple times for F(6)F(6)).

๐Ÿ”ง Approach

  1. Base cases: if n=0n = 0, return 0. If n=1n = 1, return 1.
  2. Recursive case: return fib(nโˆ’1)+fib(nโˆ’2)\text{fib}(n-1) + \text{fib}(n-2).
  3. Each call branches into two sub-calls, creating a binary recursion tree.

โšก Complexity Analysis

Time

O(2N)O(2^N) โ€” exponential, because each call generates two new calls. Very slow for N>30N > 30.

Space

O(N)O(N) โ€” the maximum depth of the recursion tree is NN

โš ๏ธ Common Mistakes

  • Not having two base cases (both n=0n = 0 and n=1n = 1 are needed)
  • Assuming this approach is efficient โ€” it is O(2N)O(2^N) and should be memoized for real use
  • Off-by-one errors in sequence indexing (F(6)=8F(6) = 8 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 O(N)O(N), and dynamic programming.