Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define the memoization cache as a mutable HashMap.
DSA Rust
use std::collections::HashMap;
fn fib(n: u32, memo: &mut HashMap<u32, u64>) -> u64 {
if n <= 1 {
return n as u64;
}
if let Some(&result) = memo.get(&n) {
return result;
}
let result = fib(n - 1, memo) + fib(n - 2, memo);
memo.[1](n, result);
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using get instead of insert to add to the cache.
Trying to remove or clear the cache instead of inserting.
✗ Incorrect
We use the insert method to add the computed result to the memoization cache.
2fill in blank
mediumComplete the code to check if the result for n is already computed in the memo cache.
DSA Rust
if let Some(&result) = memo.[1](&n) { return result; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using insert instead of get to check the cache.
Using contains_key but not retrieving the value.
✗ Incorrect
The get method returns an Option with the value if the key exists, which we can use to check the cache.
3fill in blank
hardFix the error in the recursive call to fib by correctly passing the memo parameter.
DSA Rust
let result = fib(n - 1, [1]) + fib(n - 2, memo);
Attempts:
3 left
💡 Hint
Common Mistakes
Passing `&mut memo` causing type mismatch (double mutable reference).
Passing `&memo` causing immutable reference error.
Cloning `memo` unnecessarily causing performance issues.
✗ Incorrect
The memo parameter is already a mutable reference (&mut HashMap), so pass `memo` directly to recursive calls to allow updates.
4fill in blank
hardFill both blanks to complete the memoized Fibonacci function with correct base case and recursive calls.
DSA Rust
fn fib(n: u32, memo: &mut HashMap<u32, u64>) -> u64 {
if n [1] 1 {
return n as u64;
}
if let Some(&result) = memo.get(&n) {
return result;
}
let result = fib(n - 1, [2]) + fib(n - 2, memo);
memo.insert(n, result);
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using `<` instead of `<=` in base case causing wrong results.
Passing `&memo` or `&mut memo` instead of `memo` causing type or borrow errors.
✗ Incorrect
The base case checks if n is less than or equal to 1. Recursive calls pass `memo` directly to allow cache updates.
5fill in blank
hardFill all three blanks to create a memoized function that computes factorial with caching.
DSA Rust
fn factorial(n: u32, memo: &mut HashMap<u32, u64>) -> u64 {
if n [1] 1 {
return 1;
}
if let Some(&result) = memo.get(&n) {
return result;
}
let result = n as u64 * factorial(n - 1, [2]);
memo.[3](n, result);
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of <= in base case.
Passing wrong form like &memo or &mut memo instead of memo.
Using get or remove instead of insert to update cache.
✗ Incorrect
Base case uses <= 1. Recursive call passes `memo`. Insert adds the computed factorial to the cache.
