Fibonacci Using Recursion in DSA Java - Time & Space Complexity
We want to understand how the time needed to find a Fibonacci number grows as the input number gets bigger.
Specifically, how many steps does the recursive method take as the input increases?
Analyze the time complexity of the following code snippet.
public int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
This code calculates the nth Fibonacci number by calling itself twice for smaller values until it reaches the base cases.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two recursive calls per function call.
- How many times: Each call splits into two more calls until reaching base cases, causing many repeated calculations.
Each call creates two more calls, so the total calls grow very fast as n increases.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 177 calls |
| 20 | About 21,891 calls |
| 30 | About 2,692,537 calls |
Pattern observation: The number of calls roughly doubles with each increase in n, leading to exponential growth.
Time Complexity: O(2^n)
This means the time needed grows very fast, doubling with each step up in n, making it inefficient for large inputs.
[X] Wrong: "The recursive Fibonacci runs in linear time because it just counts down from n to 0."
[OK] Correct: Each call makes two more calls, so the total calls grow exponentially, not linearly.
Understanding this helps you explain why naive recursion can be slow and why techniques like memoization improve performance.
"What if we add memoization to store results of previous calls? How would the time complexity change?"
Practice
Solution
Step 1: Understand Fibonacci sequence definition
The Fibonacci sequence is defined such that each number is the sum of the two numbers before it.Step 2: Relate to recursion
Recursion calls the function for the two previous numbers and adds their results to get the current number.Final Answer:
Each number is the sum of the two preceding numbers -> Option BQuick Check:
Fibonacci = sum of two previous numbers [OK]
- Thinking Fibonacci multiplies previous numbers
- Confusing difference with sum
- Assuming Fibonacci squares previous number
Solution
Step 1: Identify correct base case condition
The base case must check if n is 0 or 1 using '==' for comparison and logical OR '||'.Step 2: Check syntax correctness
if (n == 0 || n == 1) return n; uses correct comparison operators and logical OR. Others use incorrect operators or logic.Final Answer:
if (n == 0 || n == 1) return n; -> Option AQuick Check:
Base case uses '==' and '||' [OK]
- Using '=' instead of '==' for comparison
- Using '&&' instead of '||' in base case
- Incorrect negation or logic in condition
public class FibTest {
public static int fib(int n) {
if (n == 0 || n == 1) return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
System.out.println(fib(4));
}
}Solution
Step 1: Calculate fib(4) using recursion
fib(4) = fib(3) + fib(2) - fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + 1 = (1 + 0) + 1 = 2 - fib(2) = fib(1) + fib(0) = 1 + 0 = 1 So fib(4) = 2 + 1 = 3Step 2: Confirm output printed
The main method prints fib(4), which is 3.Final Answer:
3 -> Option DQuick Check:
fib(4) = 3 [OK]
- Confusing fib(4) with fib(5)
- Miscomputing base cases
- Adding wrong recursive results
public static int fib(int n) {
if (n == 0 || n == 1) {
return 0;
}
return fib(n - 1) + fib(n - 2);
}Solution
Step 1: Analyze base case return value
The base case returns 0 for both n=0 and n=1, but fib(1) should return 1.Step 2: Correct base case return
Return n for base cases 0 and 1 to correctly represent Fibonacci values.Final Answer:
Change 'return 0;' to 'return n;' in base case -> Option AQuick Check:
Base case returns n for n=0 or 1 [OK]
- Returning 0 for fib(1)
- Changing base case condition incorrectly
- Removing base case causing infinite recursion
Solution
Step 1: Understand recursion inefficiency
Recursive Fibonacci recalculates the same values many times, causing slow performance.Step 2: Apply memoization
Memoization stores results of fib(n) in a cache so repeated calls return cached values, improving speed.Final Answer:
Use memoization to store and reuse computed results -> Option CQuick Check:
Memoization avoids repeated calculations [OK]
- Changing base case incorrectly
- Using infinite loops causing crashes
- Counting calls without optimization
Ready to prove it?
Pass the test and this pattern moves unknown
