Problem overview
The function invert_dictionary receives a HashMap<String, String>, d, and returns a new one with keys and values swapped. Every value of d becomes a key, and it maps to the key it came from. All values of d are different, so the result has as many entries as d. The order of the entries doesn't matter.
For {"apple": "red", "banana": "yellow", "plum": "purple"} the result is {"red": "apple", "yellow": "banana", "purple": "plum"}. In {"a": "b", "b": "c"}, the string "b" is a key and also a value. That causes no trouble: the entry "a": "b" becomes "b": "a", and "b": "c" becomes "c": "b".
Approach: turn each entry around
Visit every entry of d once and insert it into a fresh map with the two parts exchanged. Since the new map is separate from d, an entry never interferes with another one, even when a string appears on both sides.
Step by step
- Create the empty map
result, a mutableHashMap<String, String>. - Loop over
ditself, without&, with the pattern(key, value). Each entry comes out as a pair of owned strings. - Insert the swapped pair: the old
valueis the new key, and the oldkeyis the new value. - Return
resultafter the loop.
The solution in Rust
impl Solution {
fn invert_dictionary(d: HashMap<String, String>) -> HashMap<String, String> {
let mut result: HashMap<String, String> = HashMap::new();
for (key, value) in d {
result.insert(value, key);
}
return result;
}
}
The Rust details worth a closer look:
- Consuming the map.
for (key, value) in dtakes ownership ofdand hands out each entry as a(String, String)tuple. The strings are moved intoresult, so nothing is copied. The cost is thatdcan't be used after the loop. Looping over&dwould give&Stringpairs, and then each string would needclone(). - Destructuring. The pattern
(key, value)splits each tuple into two variables in one step. - Argument order of
insert.insert(k, v)takes the key first. Writinginsert(value, key)is the whole swap. - Return value of
insert. It returns anOptionwith the old value if the key already existed. The lesson ignores it, because the values are distinct and no key repeats.
Tracing the example with a shared string
Take {"a": "b", "b": "c"}. The loop meets the entries in some order, because a HashMap has no defined one. Whichever comes first, the result is the same. The entry ("a", "b") inserts "b" with "a", and the entry ("b", "c") inserts "c" with "b". The two inserts use different new keys, "b" and "c", so neither overwrites the other. Reading and writing happen in two separate maps, which is why the shared string "b" causes no trouble.
Each entry costs one insertion, so the work grows in proportion to the size of d, and the new map holds the same number of entries.
Edge cases and common mistakes
- Repeated values. If two keys shared a value, the swapped map would have a repeated key, and the later insert would replace the earlier one.
{"a": "x", "b": "x"}would give a map with one entry. That is why the lesson requires distinct values. - Using
dafter the loop. The compiler reports thatdwas moved. Borrow with&dand clone the strings if you still need it. - Swapped arguments.
result.insert(key, value)just copies the map without inverting it. - One entry.
{"cat": "dog"}gives{"dog": "cat"}.
Testing
Sorted by key, the results are:
{"apple": "red", "banana": "yellow", "plum": "purple"}givespurple: plum,red: apple,yellow: banana.{"cat": "dog"}givesdog: cat.{"a": "b", "b": "c"}givesb: a,c: b.
