Challenge - 5 Problems
Memoization Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Fibonacci with Memoization
What is the output of the following C code that uses memoization to compute Fibonacci numbers?
DSA C
#include <stdio.h> int fib(int n, int memo[]) { if (n <= 1) return n; if (memo[n] != -1) return memo[n]; memo[n] = fib(n-1, memo) + fib(n-2, memo); return memo[n]; } int main() { int n = 5; int memo[6]; for (int i = 0; i <= n; i++) memo[i] = -1; int result = fib(n, memo); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Recall that Fibonacci sequence starts with 0, 1, 1, 2, 3, 5...
✗ Incorrect
The 5th Fibonacci number (0-based index) is 5. The memo array stores intermediate results to avoid repeated calculations.
🧠 Conceptual
intermediate1:30remaining
Memoization Purpose in Recursion
What is the main purpose of using memoization in recursive functions?
Attempts:
2 left
💡 Hint
Think about how recursion can repeat the same work multiple times.
✗ Incorrect
Memoization saves results of expensive function calls and returns the cached result when the same inputs occur again, improving efficiency.
🔧 Debug
advanced2:00remaining
Identify the Error in Memoized Fibonacci
What error will occur when running this code snippet?
DSA C
#include <stdio.h> int fib(int n, int memo[]) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; memo[n] = fib(n-1, memo) + fib(n-2, memo); return memo[n]; } int main() { int n = 5; int memo[6] = {0}; int result = fib(n, memo); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Check how memo array is initialized and how memo[n] is checked before recursion.
✗ Incorrect
Since Fibonacci numbers are positive and fib(0)=0, using 0 as uninitialized marker works. The code correctly computes fib(5)=5.
❓ Predict Output
advanced2:00remaining
Output of Factorial with Memoization
What is the output of this C program that uses memoization to compute factorial?
DSA C
#include <stdio.h> int fact(int n, int memo[]) { if (n <= 1) return 1; if (memo[n] != 0) return memo[n]; memo[n] = n * fact(n-1, memo); return memo[n]; } int main() { int n = 4; int memo[5] = {0}; int result = fact(n, memo); printf("%d\n", result); return 0; }
Attempts:
2 left
💡 Hint
Recall factorial 4! = 4*3*2*1
✗ Incorrect
The factorial of 4 is 24. Memoization stores intermediate factorial values to avoid repeated calculations.
🚀 Application
expert2:30remaining
Memoization Impact on Time Complexity
Consider a naive recursive function to compute Fibonacci numbers with exponential time complexity. After adding memoization, what is the new time complexity?
Attempts:
2 left
💡 Hint
Memoization avoids repeated calls by storing results.
✗ Incorrect
Memoization reduces the exponential time complexity O(2^n) of naive recursion to linear O(n) by caching results.