Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the memo array with -1.
DSA Java
int[] memo = new int[n + 1]; for (int i = 0; i < memo.length; i++) { memo[i] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing memo with 0 which can cause confusion with computed zero values.
✗ Incorrect
We use -1 to indicate that the value has not been computed yet in memoization.
2fill in blank
mediumComplete the code to check if the result is already computed in memo.
DSA Java
if (memo[n] != [1]) { return memo[n]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 0 instead of -1, causing incorrect reuse of uninitialized values.
✗ Incorrect
If memo[n] is not -1, it means the value was computed before and can be returned directly.
3fill in blank
hardFix the error in the recursive call to compute the Fibonacci number with memoization.
DSA Java
public int fib(int n, int[] memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fib([1], memo) + fib(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n or n-2 for both recursive calls, which is incorrect.
✗ Incorrect
The Fibonacci number is computed as fib(n-1) + fib(n-2), so the first recursive call must be fib(n-1).
4fill in blank
hardFill both blanks to complete the memoized factorial function.
DSA Java
public int factorial(int n, int[] memo) {
if (n <= 1) return 1;
if (memo[n] != [1]) return memo[n];
memo[n] = n * factorial([2], memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of -1 for memo check.
Calling factorial with n instead of n-1.
✗ Incorrect
We check if memo[n] is not -1 to reuse computed values, and recursively call factorial with n-1.
5fill in blank
hardFill all three blanks to complete the memoized function for computing the nth Tribonacci number.
DSA Java
public int tribonacci(int n, int[] memo) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
if (memo[n] != [1]) return memo[n];
memo[n] = tribonacci([2], memo) + tribonacci([3], memo) + tribonacci(n - 3, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong indices in recursive calls.
Checking memo with 0 instead of -1.
✗ Incorrect
We check memo[n] against -1, then compute tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3).
