Start learning free

LESSON 234 OF 293 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a HashMap in Rust: Swapping Keys and Values

Practice Read the full explanation

Given a HashMap d whose keys and values are strings, return a new HashMap with the keys and values swapped: every value of d becomes a key, and it maps to the key it belonged to.

The order of the entries in the HashMap you return doesn't matter.

Example 1:

Input: d = {"apple": "red", "banana": "yellow", "plum": "purple"}
Output: {"red": "apple", "yellow": "banana", "purple": "plum"}
Explanation: "apple" mapped to "red", so now "red" maps to "apple". The other two entries turn around the same way.

Example 2:

Input: d = {"cat": "dog"}
Output: {"dog": "cat"}
Explanation: One entry gives one entry, turned around.

Example 3:

Input: d = {"a": "b", "b": "c"}
Output: {"b": "a", "c": "b"}
Explanation: "b" is both a key and a value of d. As the value of "a", it becomes a key that maps to "a". As a key, its entry "b": "c" turns into "c": "b".

Rules:

  • d has at least one entry.
  • All the values of d are different, so the result has as many entries as d.
  • Keys and values are words without spaces.
STEP 1 OF 4
    Ctrl + Enter to check

    RUST · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Rust, explained

    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

    1. Create the empty map result, a mutable HashMap<String, String>.
    2. Loop over d itself, without &, with the pattern (key, value). Each entry comes out as a pair of owned strings.
    3. Insert the swapped pair: the old value is the new key, and the old key is the new value.
    4. Return result after 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 d takes ownership of d and hands out each entry as a (String, String) tuple. The strings are moved into result, so nothing is copied. The cost is that d can't be used after the loop. Looping over &d would give &String pairs, and then each string would need clone().
    • 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. Writing insert(value, key) is the whole swap.
    • Return value of insert. It returns an Option with 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 d after the loop. The compiler reports that d was moved. Borrow with &d and 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"} gives purple: plum, red: apple, yellow: banana.
    • {"cat": "dog"} gives dog: cat.
    • {"a": "b", "b": "c"} gives b: a, c: b.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free