Challenge - 5 Problems
Dynamic Programming Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Fibonacci Without Memoization
What is the output of the following TypeScript code that calculates Fibonacci numbers using simple recursion without any optimization?
DSA Typescript
function fib(n: number): number {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Remember that fib(0) = 0, fib(1) = 1, and fib(n) = fib(n-1) + fib(n-2).
✗ Incorrect
The function calculates Fibonacci numbers recursively. fib(5) = fib(4) + fib(3) = 3 + 2 = 5.
🧠 Conceptual
intermediate1:30remaining
Why Recursion Alone Can Be Inefficient
Which of the following best explains why simple recursion can be inefficient for problems like Fibonacci sequence calculation?
Attempts:
2 left
💡 Hint
Think about how many times fib(2) is calculated in fib(5).
✗ Incorrect
Simple recursion recalculates the same subproblems many times, which leads to exponential time complexity and inefficiency.
❓ Predict Output
advanced2:00remaining
Output of Fibonacci with Memoization
What is the output of this TypeScript code that uses memoization to optimize Fibonacci calculation?
DSA Typescript
function fibMemo(n: number, memo: {[key: number]: number} = {}): number {
if (n <= 1) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}
console.log(fibMemo(10));Attempts:
2 left
💡 Hint
Recall the Fibonacci sequence: 0,1,1,2,3,5,8,13,21,34,55,...
✗ Incorrect
fibMemo(10) returns the 10th Fibonacci number which is 55. Memoization avoids repeated calculations.
🧠 Conceptual
advanced1:30remaining
When to Use Dynamic Programming Instead of Recursion
Which scenario best describes when dynamic programming is preferred over simple recursion?
Attempts:
2 left
💡 Hint
Think about problems where the same smaller problems appear multiple times.
✗ Incorrect
Dynamic programming is best when problems have overlapping subproblems and optimal substructure, allowing reuse of results to improve efficiency.
🔧 Debug
expert2:30remaining
Identify the Error in Recursive Fibonacci with Memoization
What error does the following TypeScript code produce when calling fibMemo(5)?
DSA Typescript
function fibMemo(n: number, memo: {[key: number]: number} = {}): number {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}
console.log(fibMemo(5));Attempts:
2 left
💡 Hint
Check how the memo object is checked before returning stored values.
✗ Incorrect
The condition 'if (memo[n])' fails when memo[n] is 0, which is falsy, causing repeated calls and incorrect behavior.