Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a mutable HashMap for memoization.
DSA Rust
let mut memo: std::collections::HashMap<u32, u32> = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using Vec or HashSet instead of HashMap.
✗ Incorrect
We use HashMap::new() to create an empty map for memoization.
2fill in blank
mediumComplete the code to check if the result for n is already memoized.
DSA Rust
if let Some(&result) = memo.[1](&n) { return result; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using insert or contains_key which do not return the value.
✗ Incorrect
We use get to check if n is in the memo map.
3fill in blank
hardFix the error in inserting the computed result into the memo map.
DSA Rust
memo.[1](n, result);Attempts:
3 left
💡 Hint
Common Mistakes
Using get or contains_key which do not insert values.
✗ Incorrect
Use insert to add the computed result to the memo map.
4fill in blank
hardFill both blanks to complete the recursive Fibonacci function with memoization.
DSA Rust
fn fib(n: u32, memo: &mut std::collections::HashMap<u32, u32>) -> u32 {
if n <= 1 {
return n;
}
if let Some(&result) = memo.[1](&n) {
return result;
}
let result = fib(n - 1, memo) + fib(n - 2, memo);
memo.[2](n, result);
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping get and insert methods.
✗ Incorrect
Use get to check memo and insert to store the result.
5fill in blank
hardFill all three blanks to create a memoized factorial function.
DSA Rust
fn factorial(n: u32, memo: &mut std::collections::HashMap<u32, u32>) -> u32 {
if n <= 1 {
return 1;
}
if let Some(&result) = memo.[1](&n) {
return result;
}
let result = n * factorial(n [2] 1, memo);
memo.[3](n, result);
result
}Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - in recursion.
Swapping insert and get.
✗ Incorrect
Use get to check memo, subtract 1 in recursion, and insert to store result.
