📖 Scenario: Imagine you are organizing a small library. You want to quickly find books by their titles. To do this, you decide to use a hash table, which helps you store and find books fast using a special code called a hash.
🎯 Goal: You will create a simple hash table using a Rust Vec to store book titles. You will write a hash function to convert book titles into numbers that tell you where to store each book in the table.
📋 What You'll Learn
Create a vector called hash_table with 10 empty slots (each slot is an empty vector of strings).
Create a hash function called simple_hash that takes a string and returns a number between 0 and 9.
Use the hash function to find the correct slot for a book title and add the title to that slot.
Print the entire hash table to see where each book is stored.
💡 Why This Matters
🌍 Real World
Hash tables are used in many applications like databases, caches, and programming language implementations to quickly find data by keys.
💼 Career
Understanding hash tables and hash functions is important for software developers, especially those working with data storage, retrieval, and optimization.
Progress0 / 4 steps
1
Create the hash table structure
Create a variable called hash_table that is a Vec with 10 empty Vec<String> slots.
DSA Rust
Hint
Use vec![Vec::new(); 10] to create 10 empty vectors inside the main vector.
2
Write the hash function
Write a function called simple_hash that takes a &str called key and returns a usize. The function should add the ASCII values of all characters in key and return the sum modulo 10.
DSA Rust
Hint
Loop over each character in the string, convert it to a number, add it to a sum, then use % 10 to keep the result between 0 and 9.
3
Add book titles to the hash table
Inside main, create a vector called books with these exact titles: "Rust Book", "Data Structures", "Algorithms". Use a for loop with variable book to iterate over books. For each book, find the index by calling simple_hash(book) and push the book.to_string() into hash_table[index].
DSA Rust
Hint
Use vec![...] to create the books list. Then loop over it, get the index from simple_hash, and push the book string into the correct slot.
4
Print the hash table
Add a for loop with variables index and slot using hash_table.iter().enumerate(). Inside the loop, print the index and the slot vector using println!("Slot {}: {:?}", index, slot).
DSA Rust
Hint
Use enumerate() to get the index and iter() to loop over the hash_table. Print each slot with its index.
Practice
(1/5)
1. What is the main purpose of a hash function in a hash table?
easy
A. To sort the keys in ascending order
B. To convert a key into an index for storing values
C. To encrypt the data stored in the table
D. To count the number of elements in the table
Solution
Step 1: Understand the role of a hash function
A hash function takes a key and converts it into a number that can be used as an index in the hash table.
Step 2: Identify the correct purpose
This index helps to quickly find where the value related to the key is stored.
Final Answer:
To convert a key into an index for storing values -> Option B
Quick Check:
Hash function = key to index [OK]
Hint: Hash function maps keys to indexes fast [OK]
Common Mistakes:
Thinking hash functions sort keys
Confusing hashing with encryption
Believing hash functions count elements
2. Which of the following is the correct way to declare a hash map in Rust?
easy
A. let mut map = HashMap::new();
B. let map = new HashMap();
C. HashMap map = new HashMap();
D. var map = HashMap();
Solution
Step 1: Recall Rust syntax for hash maps
In Rust, hash maps are created using HashMap::new() and usually declared mutable with let mut.
Step 2: Check each option
let mut map = HashMap::new(); uses correct Rust syntax. Options A, B, and C use syntax from other languages or incorrect Rust syntax.
Using syntax from other languages like Java or JavaScript
Forgetting to make the map mutable
Missing the HashMap:: prefix
3. What will be the output of the following Rust code?
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("apple", 3);
map.insert("banana", 2);
map.insert("apple", 5);
println!("{:?}", map.get("apple"));
}
medium
A. Error: duplicate key
B. Some(3)
C. None
D. Some(5)
Solution
Step 1: Understand insert behavior in HashMap
In Rust's HashMap, inserting a value with an existing key replaces the old value.
Step 2: Trace the inserts and get
First insert: "apple" -> 3, second insert: "banana" -> 2, third insert: "apple" -> 5 replaces 3. So map.get("apple") returns Some(5).
Final Answer:
Some(5) -> Option D
Quick Check:
Last insert replaces value = Some(5) [OK]
Hint: Last insert with same key overwrites value [OK]
Common Mistakes:
Assuming duplicate keys cause error
Thinking old value remains after insert
Expecting None for existing key
4. Identify the error in this Rust code snippet using a hash map:
use std::collections::HashMap;
fn main() {
let map = HashMap::new();
map.insert("key", 10);
println!("{:?}", map.get("key"));
}
medium
A. HashMap is not imported
B. get method does not exist
C. map is immutable but insert is called
D. Missing semicolon after insert
Solution
Step 1: Check mutability of map
The map is declared with let (immutable) but insert tries to modify it.
Step 2: Identify the error cause
In Rust, to modify a HashMap, it must be declared mutable with let mut.
Final Answer:
map is immutable but insert is called -> Option C
Quick Check:
Insert needs mutable map [OK]
Hint: Use let mut for hash maps you modify [OK]
Common Mistakes:
Forgetting to import HashMap
Assuming get method is missing
Thinking semicolon is missing
5. You want to create a hash function for strings that sums the ASCII values of characters and then takes modulo with table size. Which of these Rust functions correctly implements this?
hard
A. fn hash(key: &str, size: usize) -> usize { key.bytes().map(|b| b as usize).sum::<usize>() % size }
The function must sum ASCII values of all characters and then take modulo with size.
Step 2: Analyze each option
fn hash(key: &str, size: usize) -> usize { key.bytes().map(|b| b as usize).sum::<usize>() % size } sums bytes (ASCII values) and mods by size correctly. Options A, B, and D only use length or count, not sum of ASCII values.
Final Answer:
fn hash(key: &str, size: usize) -> usize { key.bytes().map(|b| b as usize).sum::<usize>() % size } -> Option A
Quick Check:
Sum ASCII bytes then mod size = fn hash(key: &str, size: usize) -> usize { key.bytes().map(|b| b as usize).sum::<usize>() % size } [OK]
Hint: Sum bytes, then modulo table size for hash [OK]
Common Mistakes:
Using length instead of sum of ASCII values
Using chars count instead of bytes
Forgetting to modulo by table size
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.