Challenge - 5 Problems
Fibonacci Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Fibonacci Call
What is the output of the following Java code that prints Fibonacci numbers using recursion?
DSA Java
public class Fibonacci { public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { for (int i = 0; i < 6; i++) { System.out.print(fib(i) + " "); } } }
Attempts:
2 left
💡 Hint
Remember that fib(0) = 0 and fib(1) = 1 in this code.
✗ Incorrect
The recursive function returns n when n is 0 or 1, so fib(0) = 0 and fib(1) = 1. The loop prints fib(0) to fib(5), which are 0, 1, 1, 2, 3, 5.
🧠 Conceptual
intermediateNumber of Recursive Calls for fib(4)
How many total calls to the fib function are made when computing fib(4) using the recursive method below?
DSA Java
public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }
Attempts:
2 left
💡 Hint
Draw the call tree for fib(4) to count all calls.
✗ Incorrect
fib(4) calls fib(3) and fib(2). fib(3) calls fib(2) and fib(1), fib(2) calls fib(1) and fib(0), and so on. Counting all calls results in 9 total calls.
🔧 Debug
advancedIdentify the Error in Fibonacci Code
What error will occur when running this Java code to compute Fibonacci numbers recursively?
DSA Java
public class Fibonacci { public static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 3); } public static void main(String[] args) { System.out.println(fib(4)); } }
Attempts:
2 left
💡 Hint
Check the recursive calls and see if they always reduce n properly.
✗ Incorrect
The recursive call fib(n - 3) can cause negative arguments for n < 3, leading to infinite recursion and eventually StackOverflowError.
❓ Predict Output
advancedOutput of Memoized Fibonacci Code
What is the output of this Java code that uses memoization to compute Fibonacci numbers?
DSA Java
import java.util.HashMap; public class Fibonacci { static HashMap<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 result = fib(n - 1) + fib(n - 2); memo.put(n, result); return result; } public static void main(String[] args) { for (int i = 0; i < 7; i++) { System.out.print(fib(i) + " "); } } }
Attempts:
2 left
💡 Hint
Memoization stores results to avoid repeated calculations.
✗ Incorrect
The memoized fib function returns correct Fibonacci numbers starting from 0,1,... up to fib(6) = 8.
🧠 Conceptual
expertTime Complexity of Recursive Fibonacci Without Memoization
What is the time complexity of the naive recursive Fibonacci function without memoization?
Attempts:
2 left
💡 Hint
Consider how many calls are made as n increases.
✗ Incorrect
Each call to fib(n) makes two calls to fib(n-1) and fib(n-2), leading to exponential growth in calls, so time complexity is O(2^n).
