Challenge - 5 Problems
Master of Overlapping Subproblems and Optimal Substructure
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Fibonacci with Memoization
What is the output of the following JavaScript code that calculates Fibonacci numbers using memoization?
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Remember that Fibonacci sequence starts with 0, 1, 1, 2, 3, 5...
✗ Incorrect
The Fibonacci sequence for n=5 is 5. The function uses memoization to avoid repeated calculations.
🧠 Conceptual
intermediateIdentifying Overlapping Subproblems
Which of the following problems best demonstrates the concept of overlapping subproblems?
Attempts:
2 left
💡 Hint
Overlapping subproblems means the same smaller problems are solved multiple times.
✗ Incorrect
Computing Fibonacci numbers recursively without memoization solves the same subproblems repeatedly, showing overlapping subproblems.
❓ Predict Output
advancedOutput of Coin Change Problem with Memoization
What is the output of the following JavaScript code that finds the minimum number of coins needed to make change?
DSA Javascript
function minCoins(coins, amount, memo = {}) {
if (amount === 0) return 0;
if (amount < 0) return Infinity;
if (memo[amount]) return memo[amount];
let min = Infinity;
for (let coin of coins) {
const res = minCoins(coins, amount - coin, memo);
if (res !== Infinity && res + 1 < min) {
min = res + 1;
}
}
memo[amount] = min;
return min;
}
console.log(minCoins([1, 3, 4], 6));Attempts:
2 left
💡 Hint
Try to find the fewest coins that sum to 6 using coins 1, 3, and 4.
✗ Incorrect
The minimum coins to make 6 are 2 (e.g., 3 + 3).
🔧 Debug
advancedIdentify the Error in Memoized Fibonacci
What error does the following code produce when run?
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2);
return memo[n];
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Check if all recursive calls pass the memo object.
✗ Incorrect
No runtime error occurs and the code outputs 5. However, the fib(n - 2) call misses the memo argument, so it uses a new memo object instead of the shared one.
🧠 Conceptual
expertOptimal Substructure in Dynamic Programming
Which statement best describes the property of optimal substructure in dynamic programming?
Attempts:
2 left
💡 Hint
Think about how solutions to smaller parts help build the full solution.
✗ Incorrect
Optimal substructure means the best solution to a problem can be made from best solutions of smaller parts.
