4. Identify the error in this TypeScript DP Fibonacci code and select the fix:
function fib(n: number): number {
const dp: number[] = new Array(n).fill(0);
dp[0] = 0;
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
medium
A. Change array size to n+1.
B. Initialize dp[2] to 1 before the loop.
C. Start loop from i = 1 instead of 2.
D. Remove dp[0] initialization.
Solution
Step 1: Analyze array size and access
Array dp has size n, but loop accesses dp[n] beyond the initial length.
Step 2: Fix array size
Increase dp size to n+1 to safely access dp[n].
Final Answer:
Change array size to n+1 to avoid out-of-bounds error. -> Option A
Quick Check:
Array size must cover dp[n] [OK]
Hint: Array size must be n+1 for dp[n] access [OK]
Common Mistakes:
Ignoring array size mismatch
Starting loop incorrectly
Unnecessary dp initialization changes
5. You want to optimize the space used by the DP Fibonacci function. Which modification correctly reduces space complexity from O(n) to O(1)?
hard
A. Use a recursive function without memoization.
B. Store all Fibonacci numbers in a global array.
C. Use two variables to store only the last two Fibonacci numbers instead of an array.
D. Initialize the dp array with zeros and fill it completely every call.
Solution
Step 1: Understand space usage in DP Fibonacci
DP uses an array of size n+1, so space is O(n).
Step 2: Optimize space by storing only needed values
Since each Fibonacci number depends only on the previous two, storing just two variables suffices.
Step 3: Compare options
Use two variables to store only the last two Fibonacci numbers instead of an array. uses two variables, reducing space to O(1). Others do not reduce space or are inefficient.
Final Answer:
Use two variables to store only the last two Fibonacci numbers instead of an array. -> Option C
Quick Check:
Two vars = O(1) space [OK]
Hint: Keep only last two Fibonacci numbers to save space [OK]
Common Mistakes:
Using recursion without memoization increases time
Storing all numbers globally wastes space
Filling full dp array every call wastes memory
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.