Challenge - 5 Problems
Hash Table Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code using a hash map?
Consider the following Rust code that inserts key-value pairs into a hash map and then prints the value for key 2. What will it print?
DSA Rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, "apple");
map.insert(2, "banana");
map.insert(3, "cherry");
println!("{}", map.get(&2).unwrap());
}Attempts:
2 left
💡 Hint
Look at the key used in the get method and what value was inserted for that key.
✗ Incorrect
The code inserts three key-value pairs. The key 2 is associated with "banana", so printing map.get(&2).unwrap() outputs "banana".
🧠 Conceptual
intermediateWhat is the main purpose of a hash function in a hash table?
Choose the best description of what a hash function does in a hash table.
Attempts:
2 left
💡 Hint
Think about how hash tables find values fast using keys.
✗ Incorrect
A hash function takes a key and converts it into an index where the value is stored, enabling fast access.
❓ Predict Output
advancedWhat error does this Rust code produce when inserting duplicate keys in a hash map?
Analyze the following Rust code. What will happen when it runs?
DSA Rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key", 10);
map.insert("key", 20);
println!("{}", map.get(&"key").unwrap());
}Attempts:
2 left
💡 Hint
Think about what happens when you insert a value with a key that already exists.
✗ Incorrect
In Rust's HashMap, inserting a value with an existing key replaces the old value. So the value for "key" becomes 20.
🔧 Debug
advancedWhy does this Rust code cause a compile-time error?
Look at this Rust code that tries to use a custom struct as a key in a hash map. Why does it fail to compile?
DSA Rust
use std::collections::HashMap; #[derive(Debug)] struct Point { x: i32, y: i32, } fn main() { let mut map = HashMap::new(); let p = Point { x: 1, y: 2 }; map.insert(p, "origin"); }
Attempts:
2 left
💡 Hint
HashMap keys must implement certain traits to be used as keys.
✗ Incorrect
Rust requires keys in HashMap to implement Eq and Hash traits. The Point struct only derives Debug, so it cannot be used as a key.
🚀 Application
expertHow many items are in the hash map after this Rust code runs?
Given the following Rust code, how many key-value pairs does the hash map contain at the end?
DSA Rust
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
for i in 0..5 {
map.insert(i % 3, i);
}
println!("{}", map.len());
}Attempts:
2 left
💡 Hint
Consider how keys repeat when using i % 3 and how insert replaces values.
✗ Incorrect
Keys are 0,1,2 repeated. Each insert with the same key replaces the old value. So only keys 0,1,2 remain, total 3 items.
