Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the memoization map for caching results.
DSA C++
std::unordered_map<int, int> [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that is not descriptive or common for memoization.
Forgetting to declare the map before using it.
✗ Incorrect
The memoization map is commonly named 'memo' to store computed results for reuse.
2fill in blank
mediumComplete the code to check if the result for 'n' is already computed in memo.
DSA C++
if ([1].find(n) != [1].end()) return [1][n];
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the memo map.
Not checking for the key before accessing the map.
✗ Incorrect
We check the 'memo' map to see if 'n' has a cached result to avoid recomputation.
3fill in blank
hardFix the error in the recursive Fibonacci function by adding memoization storage.
DSA C++
int fib(int n, std::unordered_map<int, int>& memo) {
if (n <= 1) return n;
if (memo.find(n) != memo.end()) return memo[n];
memo[n] = fib(n - 1, [1]) + fib(n - 2, memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Passing a different variable name or not passing the memo map at all.
Not storing the computed result in the memo map.
✗ Incorrect
The recursive calls must pass the same memo map to store and reuse results.
4fill in blank
hardFill both blanks to complete the memoized factorial function.
DSA C++
int factorial(int n, std::unordered_map<int, int>& memo) {
if (n <= 1) return 1;
if (memo.find(n) != memo.end()) return memo[n];
memo[n] = n [1] factorial([2], memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Using 'n + 1' instead of 'n - 1' in recursion.
✗ Incorrect
Factorial is n multiplied by factorial of (n - 1).
5fill in blank
hardFill all three blanks to create a memoized function that returns the nth Tribonacci number.
DSA C++
int tribonacci(int n, std::unordered_map<int, int>& memo) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
if (memo.find(n) != memo.end()) return memo[n];
memo[n] = tribonacci(n [1], memo) + tribonacci(n [2], memo) + tribonacci(n [3], memo);
return memo[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction in indices.
Using wrong indices like '+ 1' which causes infinite recursion.
✗ Incorrect
Tribonacci is sum of previous three numbers: n-1, n-2, and n-3.
