Start learning free

LESSON 227 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in C++: Swapping Keys and Values

Practice Read the full explanation

Given an unordered_map d whose keys and values are strings, return a new unordered_map 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 unordered_map 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

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in C++, explained

    Problem overview

    The function invertDictionary receives an unordered_map<string, string> named d and returns a new map with keys and values swapped: every value of d becomes a key, and it maps to the key it came from. All the 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"}. For {"cat": "dog"} it is {"dog": "cat"}. For {"a": "b", "b": "c"} it is {"b": "a", "c": "b"}: the word "b" is a value in the first entry and a key in the second, and each entry turns around on its own.

    Approach: one pass, one swap per entry

    Every entry of d is a pair, and inverting the map means writing each pair backwards into a new map. Nothing about one entry depends on another, so a single loop over d is enough. The swapped pairs go into a new map, not into d, because adding or removing entries of a container while you loop over it is unsafe.

    Step by step

    1. Create result. An empty unordered_map<string, string> that will hold the swapped pairs.
    2. Loop over the entries of d. for (auto &[key, value] : d) goes through each pair and gives its two parts the names key and value.
    3. Store the swapped pair. result[value] = key; makes the old value the new key. Since the values are all different, no two entries use the same new key, and none is lost.
    4. Return result.

    The solution in C++

    class Solution {
    public:
        unordered_map<string, string> invertDictionary(unordered_map<string, string> &d) {
            unordered_map<string, string> result;
            for (auto &[key, value] : d) {
                result[value] = key;
            }
            return result;
        }
    };
    

    The C++ details worth knowing:

    • Structured bindings. Each element of an unordered_map is a pair with a first and a second. The form auto &[key, value], available since C++17, unpacks the pair into two named variables, which reads better than entry.first and entry.second.
    • The & avoids a copy. Without it, each pair, including both strings, would be copied on every turn. With it, key and value refer to the data stored in d. The key part of a stored pair is const, so you can read it but not change it.
    • Assignment through []. result[value] = key creates the entry if the key is new and overwrites it otherwise. Here every key is new.
    • The input is passed by reference. The & in the parameter avoids copying the whole map, and the function leaves d unchanged.
    • Entry order is unspecified. The inverted map may list its entries in a different order from d.

    Complexity

    Time: O(n) on average for n entries, because each insertion into an unordered_map takes constant time on average. Space: O(n), for the new map.

    Edge cases and common mistakes

    • A word that is both a key and a value. {"a": "b", "b": "c"} works without special care. Because the swapped pairs go into a separate map, "b" can be a new key for "a" without touching its old entry in d.
    • Duplicate values. The task rules them out. If two keys shared a value, both would try to write the same new key, and one of the original keys would be lost. The result would have fewer entries than d.
    • Writing back into d. Inserting into the map you are looping over can invalidate the loop, and the result would also mix old and new entries.
    • Swapped assignment. result[key] = value just copies d.
    • One entry. {"cat": "dog"} gives {"dog": "cat"}.

    Testing

    Printed with the entries sorted by key:

    • {"apple": "red", "banana": "yellow", "plum": "purple"} gives purple: plum, red: apple, yellow: banana.
    • {"a": "b", "b": "c"} gives b: a, c: b.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free