Problem overview
The function to_dictionary receives a vector of strings, names, and a vector of integers, scores, of the same length. It returns a HashMap<String, i32> in which names[i] is a key and scores[i] is its value. The names are all different, two names may share a score, and two empty vectors give an empty map. The order of the entries doesn't matter.
For ["Ana", "Ben", "Cara"] and [90, 75, 88], the map holds Ana: 90, Ben: 75 and Cara: 88.
Approach: one index, two vectors
A name and its score sit at the same position in their vectors. So one loop over the positions reaches both of them: at each index i, insert the pair (names[i], scores[i]) into the map. The map ends up with one entry per name.
Step by step
- Create the empty map
result, a mutableHashMap<String, i32>. - Loop over the indices with
for i in 0..names.len(). The range0..names.len()covers 0 up to, but not including, the length. - Insert the pair. The key is
names[i].clone()and the value isscores[i]. - Return
resultafter the loop.
The solution in Rust
impl Solution {
fn to_dictionary(names: Vec<String>, scores: Vec<i32>) -> HashMap<String, i32> {
let mut result: HashMap<String, i32> = HashMap::new();
for i in 0..names.len() {
result.insert(names[i].clone(), scores[i]);
}
return result;
}
}
The Rust details worth a closer look:
- Why
clone(). The map's keys must own their strings. Indexingnames[i]can't move aStringout of the vector, soclone()makes a copy for the map to keep. The scores arei32values, which are copied automatically. - Ranges are half-open.
0..names.len()excludes the end, so the last index used isnames.len() - 1. For an empty vector the range is empty, the loop doesn't run, and the result is an empty map. - Indexing is bounds-checked. If
scoreswere shorter thannames,scores[i]would panic. The lesson guarantees equal lengths. - Another way.
names.into_iter().zip(scores).collect()builds the same map without indices. The lesson's loop makes each step visible.
Tracing the example
With names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88], the loop runs for i equal to 0, 1 and 2. At 0 it inserts "Ana" with 90, at 1 "Ben" with 75, and at 2 "Cara" with 88. The map then has three entries. The loop does one insertion per name, so the time grows in proportion to the number of names.
The map doesn't remember the order of insertion. Printing it may list the entries in any order, and that order can differ from one run to the next.
Looking a score up afterwards is just as direct: result["Ben"] gives 75, and result.get("Zed") returns None for a name that isn't there, where indexing with a missing key would panic.
Edge cases and common mistakes
- Same score, different names.
["Zoe", "Adam"]with[60, 60]gives two entries. Only keys must be unique; values can repeat. - Empty input. Two empty vectors return an empty map.
- Repeated names. The lesson rules them out, but with a repeated name,
insertwould replace the earlier score:["Ana", "Ana"]with[1, 2]givesAna: 2. - Using
0..=names.len(). The inclusive range would go one index too far, and indexing it would panic.
Testing
Sorted by name, the entries are:
["Ana", "Ben", "Cara"]with[90, 75, 88]givesAna: 90,Ben: 75,Cara: 88.["Zoe", "Adam"]with[60, 60]givesAdam: 60,Zoe: 60.["Max"]with[100]givesMax: 100.- Two empty vectors give an empty map.
