Module 09 Exercises — Collections & Strings
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be sure you can:
- choose between
Vec,HashMapandHashSetfor a given job, and justify it; - explain what
entry().or_insert()does in one sentence; - say why
s.len()on"héllo"is 6 and not 5.
The string drills are where most people slow down. That is expected — the UTF-8 rules are the price of never silently corrupting text, and every language that hides them from you is storing up a different bug.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 9.1 — Vec basics
Build a Vec<i32> of 1..=20, keep only multiples of 3, square them, and print the sum and
the maximum.
Solution
fn main() {
let v: Vec<i32> = (1..=20).filter(|n| n % 3 == 0).map(|n| n * n).collect();
println!("{v:?}");
println!("sum={} max={:?}", v.iter().sum::<i32>(), v.iter().max());
}🟢 Exercise 9.2 — Median and mode
Given a Vec<i32>, compute the median (sort first) and the mode (most frequent value)
using a HashMap.
Solution
use std::collections::HashMap;
fn median(v: &mut Vec<i32>) -> f64 {
v.sort();
let n = v.len();
if n % 2 == 0 { (v[n/2 - 1] + v[n/2]) as f64 / 2.0 } else { v[n/2] as f64 }
}
fn mode(v: &[i32]) -> Option<i32> {
let mut counts = HashMap::new();
for &x in v { *counts.entry(x).or_insert(0) += 1; }
counts.into_iter().max_by_key(|&(_, c)| c).map(|(val, _)| val)
}
fn main() {
let mut v = vec![4, 1, 7, 2, 4, 9, 4, 2];
println!("median={}", median(&mut v));
println!("mode={:?}", mode(&v));
}Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 9.3 — Word frequency report
Read a paragraph of text, count word frequencies case-insensitively (stripping
punctuation), and print the top 5 as word: count, sorted by count descending then
alphabetically.
Solution
use std::collections::HashMap;
fn main() {
let text = "The quick brown fox. The FOX jumps! A quick fox, the end.";
let mut counts: HashMap<String, usize> = HashMap::new();
for word in text.split_whitespace() {
let w: String = word
.chars()
.filter(|c| c.is_alphanumeric() || *c == '\'')
.collect::<String>()
.to_lowercase();
if w.is_empty() { continue; }
*counts.entry(w).or_insert(0) += 1;
}
let mut pairs: Vec<_> = counts.into_iter().collect();
pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
for (word, count) in pairs.iter().take(5) {
println!("{word}: {count}");
}
}.then() chains comparisons — descending by count, then ascending alphabetically.
🟡 Exercise 9.4 — Pig Latin
Convert each word: if it starts with a vowel, append -hay; otherwise move the first
consonant to the end and append -ay. "first" → "irst-fay", "apple" → "apple-hay".
Handle non-ASCII input without panicking.
Solution
fn pig_latin(word: &str) -> String {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) if "aeiouAEIOU".contains(first) => format!("{word}-hay"),
Some(first) => format!("{}-{}ay", chars.as_str(), first.to_lowercase()),
}
}
fn main() {
for w in "first apple ñandu strong".split_whitespace() {
print!("{} ", pig_latin(w));
}
println!();
}Using chars() rather than byte slicing is what makes ñandu safe.
🟡 Exercise 9.5 — Employee directory
Build a text-command interpreter over HashMap<String, Vec<String>> (department →
employees):
Add Sally to EngineeringList Engineering→ sorted namesList All→ all departments sorted, each with sorted employees
Solution
use std::collections::HashMap;
fn run(cmd: &str, db: &mut HashMap<String, Vec<String>>) {
let parts: Vec<&str> = cmd.split_whitespace().collect();
match parts.as_slice() {
["Add", name, "to", dept] => {
db.entry(dept.to_string()).or_default().push(name.to_string());
println!("added {name} to {dept}");
}
["List", "All"] => {
let mut depts: Vec<_> = db.keys().collect();
depts.sort();
for d in depts {
let mut names = db[d].clone();
names.sort();
println!("{d}: {}", names.join(", "));
}
}
["List", dept] => match db.get(*dept) {
Some(names) => {
let mut n = names.clone();
n.sort();
println!("{dept}: {}", n.join(", "));
}
None => println!("no such department: {dept}"),
},
_ => println!("unrecognized command: {cmd}"),
}
}
fn main() {
let mut db = HashMap::new();
for c in ["Add Sally to Engineering", "Add Amir to Sales",
"Add Bob to Engineering", "List Engineering", "List All"] {
run(c, &mut db);
}
}Matching on parts.as_slice() with slice patterns is an elegant Rust idiom worth
remembering.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 9.6 — LRU-ish cache
Implement struct Cache { map: HashMap<String, String>, order: VecDeque<String>, cap: usize }
with get(&mut self, k) -> Option<&String> (moves the key to most-recent) and
put(&mut self, k, v) (evicts the least-recently-used when over capacity).
Solution
use std::collections::{HashMap, VecDeque};
struct Cache { map: HashMap<String, String>, order: VecDeque<String>, cap: usize }
impl Cache {
fn new(cap: usize) -> Self {
Cache { map: HashMap::new(), order: VecDeque::new(), cap }
}
fn touch(&mut self, k: &str) {
if let Some(pos) = self.order.iter().position(|x| x == k) {
self.order.remove(pos);
}
self.order.push_back(k.to_string());
}
fn get(&mut self, k: &str) -> Option<&String> {
if self.map.contains_key(k) {
self.touch(k);
self.map.get(k)
} else {
None
}
}
fn put(&mut self, k: &str, v: &str) {
self.map.insert(k.to_string(), v.to_string());
self.touch(k);
while self.map.len() > self.cap {
if let Some(old) = self.order.pop_front() {
self.map.remove(&old);
}
}
}
}
fn main() {
let mut c = Cache::new(2);
c.put("a", "1");
c.put("b", "2");
c.get("a"); // a becomes most recent
c.put("c", "3"); // evicts b
assert!(c.get("b").is_none());
assert!(c.get("a").is_some());
}Note touch is a separate method: calling it inside get before self.map.get(k) keeps
the mutable and immutable borrows from overlapping. That sequencing is the borrow-checker
lesson of this exercise.
Self-check
- Why does
v.remove(0)cost O(n) whilev.swap_remove(0)is O(1)? - Why can't you index a
Stringwith an integer? - What does
entry(k).or_insert(0)return, and why does that matter? - When would you pick
BTreeMapoverHashMap? - Why does
let s3 = s1 + &s2;invalidates1?
Answers
removeshifts every later element left;swap_removejust moves the final element into the vacated slot (losing order).- UTF-8 is variable-width, so a byte index isn't a character index; Rust makes you pick
bytes(),chars(), or a slice explicitly. &mut V— so you can mutate in place with a single lookup.- When you need keys in sorted order, or range queries.
Add for Stringis implemented asfn add(self, &str)— it takesselfby value and reuses its buffer, sos1is moved.
