Challenge - 5 Problems
Dynamic Programming Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Fibonacci Without Memoization
What is the output of the following Java code that calculates Fibonacci numbers using simple recursion without any optimization?
DSA Java
public class Fib { public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { System.out.println(fib(5)); } }
Attempts:
2 left
💡 Hint
Trace the calls fib(5) = fib(4) + fib(3) and so on.
✗ Incorrect
The recursive Fibonacci function returns the sum of the two previous Fibonacci numbers. fib(5) = fib(4) + fib(3) = 3 + 2 = 5.
🧠 Conceptual
intermediateWhy Does Simple Recursion Fail for Large Inputs?
Why does simple recursion without memoization or dynamic programming fail or become inefficient for problems like Fibonacci or computing factorial for large inputs?
Attempts:
2 left
💡 Hint
Think about how many times fib(3) is calculated when calling fib(5).
✗ Incorrect
Simple recursion recalculates the same subproblems multiple times, causing exponential growth in calls and slow performance.
❓ Predict Output
advancedOutput of Fibonacci with Memoization
What is the output of this Java code that uses memoization to optimize Fibonacci calculation?
DSA Java
import java.util.HashMap; public class FibMemo { private 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) { System.out.println(fib(10)); } }
Attempts:
2 left
💡 Hint
Memoization stores results to avoid repeated calculations.
✗ Incorrect
fib(10) = 55. Memoization avoids repeated calls, so the result is computed efficiently.
🧠 Conceptual
advancedWhen to Prefer Dynamic Programming Over Simple Recursion?
In which situation is dynamic programming preferred over simple recursion?
Attempts:
2 left
💡 Hint
Dynamic programming stores results of subproblems to avoid recomputation.
✗ Incorrect
Dynamic programming is best when subproblems overlap and the problem can be broken into optimal subproblems.
🚀 Application
expertIdentify the Number of Calls in Recursive Fibonacci
How many times is the function fib called when computing fib(4) using the simple recursive method without memoization?
Attempts:
2 left
💡 Hint
Draw the recursion tree for fib(4) and 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). Counting all calls gives 9.
