Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the nth Fibonacci number using recursion.
DSA C++
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) [1] fib(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting the base case for n <= 1.
✗ Incorrect
The Fibonacci number is the sum of the two previous Fibonacci numbers, so we add fib(n-1) and fib(n-2).
2fill in blank
mediumComplete the code to memoize the Fibonacci function using a vector.
DSA C++
int fibMemo(int n, std::vector<int>& memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fibMemo(n - 1, memo) [1] fibMemo(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operators in the recursive sum.
Not storing the computed value in memo.
✗ Incorrect
Memoization stores the sum of fib(n-1) and fib(n-2) to avoid repeated calculations.
3fill in blank
hardFix the error in the bottom-up Fibonacci implementation to correctly fill the dp array.
DSA C++
int fibDP(int n) {
std::vector<int> dp(n + 1, 0);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] [1] dp[i - 2];
}
return dp[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Incorrect loop bounds.
✗ Incorrect
Each Fibonacci number is the sum of the two previous numbers in the dp array.
4fill in blank
hardComplete the space-optimized dynamic programming implementation for the nth Fibonacci number.
DSA C++
int fibSpace(int n) {
if (n <= 1) return n;
int prev = 0;
int curr = 1;
for (int i = 2; i <= n; ++i) {
int next = prev [1] curr;
prev = curr;
curr = next;
}
return curr;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong operator instead of addition.
Incorrectly updating the prev and curr variables.
✗ Incorrect
In space-optimized DP for Fibonacci, each subsequent value is the sum of the previous two values using constant extra space.
5fill in blank
hardComplete the recurrence relation in the bottom-up 0/1 Knapsack DP implementation.
DSA C++
int knapsack(int W, std::vector<int>& wt, std::vector<int>& val, int n) {
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(W + 1, 0));
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
if (wt[i - 1] <= w) {
dp[i][w] = std::max(dp[i - 1][w], val[i - 1] [1] dp[i - 1][w - wt[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][W];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max.
Wrong operator when including the item.
✗ Incorrect
The optimal substructure chooses the maximum between skipping the item or taking it (value + subproblem with reduced weight).
