Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate Fibonacci numbers using simple recursion.
DSA C
int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) [1] fib(n - 2);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to return the sum.
✗ Incorrect
The Fibonacci number is the sum of the two previous Fibonacci numbers, so we add the results of fib(n-1) and fib(n-2).
2fill in blank
mediumComplete the code to implement memoization in Fibonacci calculation.
DSA C
int fibMemo(int n, 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];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not storing the sum in memo array.
Using wrong operators causing incorrect results.
✗ 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 greedy coin change function to return minimum coins needed.
DSA C
int minCoins(int coins[], int n, int amount) {
int count = 0;
for (int i = n - 1; i >= 0; i--) {
while (amount >= coins[i]) {
amount [1] coins[i];
count++;
}
}
return amount == 0 ? count : -1;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' which increases amount causing infinite loop.
Using multiplication or division operators incorrectly.
✗ Incorrect
To reduce the amount by the coin value, we subtract coins[i] from amount using '-=' operator.
4fill in blank
hardFill both blanks to implement bottom-up DP for Fibonacci numbers.
DSA C
int fibDP(int n) {
int dp[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i [1] 1] [2] dp[i - 2];
}
return dp[n];
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operators causing index errors.
Mixing multiplication or division instead of addition.
✗ Incorrect
We calculate dp[i] by adding dp[i-1] and dp[i-2]. The first blank is '-' to access previous index, second blank is '+' to add values.
5fill in blank
hardFill all three blanks to create a greedy algorithm for activity selection problem.
DSA C
void selectActivities(int start[], int finish[], int n) {
int i = 0;
printf("Activity %d selected\n", i);
for (int j = 1; j < n; j++) {
if (start[j] [1] finish[[3]]) {
printf("Activity %d selected\n", j);
i = [2];
}
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operators causing wrong selections.
Not updating the last selected activity index correctly.
✗ Incorrect
We select activity j if its start time is greater or equal to finish time of last selected activity i. Then update i to j.