4. Identify the error in this bottom-up DP code for Fibonacci:
int n = 5;
int[] dp = new int[n];
dp[0] = 0; dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
System.out.println(dp[n]);
medium
A. Array size is too small, causing IndexOutOfBoundsException
B. Base cases dp[0] and dp[1] are incorrect
C. Loop condition should be i < n instead of i <= n
D. No error, code runs fine
Solution
Step 1: Check array size
Array dp has size n=5, valid indices 0 to 4 only.
Step 2: Loop accesses dp[5]
Loop runs i=2 to 5 inclusive, dp[5] access causes error.
Final Answer:
Array size is too small, causing IndexOutOfBoundsException -> Option A
Quick Check:
Array size must be n+1 for dp[n] access [OK]
Hint: Array size must cover all indices used in loop [OK]
Common Mistakes:
Using array size n instead of n+1
Ignoring loop boundary causing runtime error
Assuming code runs without error
5. You want to find the number of ways to climb n stairs if you can take 1 or 2 steps at a time using bottom-up DP. Which code snippet correctly implements this?
hard
A. int[] dp = new int[n+1]; dp[0]=0; dp[1]=1; for(int i=2;i<=n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n];
B. int[] dp = new int[n]; dp[0]=1; dp[1]=2; for(int i=2;i
C. int[] dp = new int[n+1]; dp[0]=1; dp[1]=1; for(int i=2;i<=n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n];
D. int[] dp = new int[n+1]; dp[0]=1; dp[1]=1; for(int i=1;i<=n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n];
Solution
Step 1: Initialize base cases for climbing stairs
dp[0]=1 means 1 way to stand still; dp[1]=1 means 1 way to climb 1 step.
Step 2: Fill dp using sum of previous two steps
For i≥2, dp[i] = dp[i-1] + dp[i-2] counts ways taking 1 or 2 steps.
Step 3: Check loop and return
Loop runs i=2 to n inclusive; return dp[n] is correct.
Final Answer:
int[] dp = new int[n+1]; dp[0]=1; dp[1]=1; for(int i=2;i<=n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n]; -> Option C