Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a struct named HashMap.
DSA Rust
struct [1] {
buckets: Vec<Vec<(String, String)>>,
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different struct name like Map or Dictionary.
✗ Incorrect
The struct name should be HashMap to match the implementation.
2fill in blank
mediumComplete the code to initialize the buckets vector with empty vectors.
DSA Rust
impl HashMap {
fn new(size: usize) -> Self {
let mut buckets = Vec::with_capacity(size);
for _ in 0..size {
buckets.push([1]);
}
HashMap { buckets }
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Vec::empty() which does not exist in Rust.
Using Vec::with_capacity(1) which creates capacity but not an empty vector.
✗ Incorrect
Each bucket is an empty vector of key-value pairs, so Vec::new() is correct.
3fill in blank
hardFix the error in the hash function to compute the bucket index.
DSA Rust
fn hash(&self, key: &str) -> usize {
let mut hash = 0;
for byte in key.bytes() {
hash = hash.wrapping_mul(31).wrapping_add(byte as usize);
}
hash [1] self.buckets.len()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using division (/) which returns quotient, not suitable for indexing.
Using multiplication (*) which increases the number.
Using addition (+) which does not limit the range.
✗ Incorrect
The modulo operator % is used to keep the hash within bucket range.
4fill in blank
hardFill both blanks to complete the insert method that adds or updates a key-value pair.
DSA Rust
fn insert(&mut self, key: String, value: String) {
let index = self.hash(&key);
let bucket = &mut self.buckets[index];
for pair in bucket.iter_mut() {
if pair.[1] == key {
pair.[2] = value;
return;
}
}
bucket.push((key, value));
}Attempts:
3 left
💡 Hint
Common Mistakes
Using push or pop instead of tuple indices.
Mixing up key and value positions.
✗ Incorrect
pair.0 is the key, pair.1 is the value in the tuple.
5fill in blank
hardFill all three blanks to complete the get method that retrieves a value by key.
DSA Rust
fn get(&self, key: &str) -> Option<&String> {
let index = self.hash(key);
let bucket = &self.buckets[index];
for pair in bucket.iter() {
if pair.[1] == key {
return Some(pair.[2]);
}
}
[3]
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning Some instead of None when key is missing.
Mixing up tuple indices.
✗ Incorrect
pair.0 is key, pair.1 is value, and None is returned if key not found.
