Start learning free

LESSON 231 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Invert a Dictionary in Kotlin: 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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Kotlin, explained

    Problem overview

    The function invertDictionary receives a Map<String, String>, d, and returns a new map where every value of d is a key that maps to the key it belonged to. For {apple=red, banana=yellow, plum=purple} the result is {red=apple, yellow=banana, purple=plum}. The values of d are all different, so no entry is lost.

    In {a=b, b=c}, the word b is both a value and a key. As a value it becomes a key that maps to a, and as a key it ends up as a value of c. The result is {b=a, c=b}, with no clash, because the old keys and the old values play separate roles.

    Approach: turn each entry around

    Each entry can be turned around on its own, so one pass over d is enough. Write each pair into a new map, with the old value as the key and the old key as the value. A new map keeps d unchanged while the loop reads it.

    Step by step

    1. Create the new map result with mutableMapOf<String, String>().
    2. Loop over the entries. for ((key, value) in d) takes each entry apart into its key and its value. The parentheses are a destructuring declaration.
    3. Store the swapped pair: result[value] = key.
    4. Return result.

    The solution in Kotlin

    class Solution {
        fun invertDictionary(d: Map<String, String>): Map<String, String> {
            val result = mutableMapOf<String, String>()
            for ((key, value) in d) {
                result[value] = key
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • Read-only parameter and result. Map in Kotlin is a read-only view: it has no put or assignment by key. The function builds a MutableMap, which is also a Map, and returns it under the declared type.
    • Destructuring entries. A map entry has two components, so (key, value) in the loop header works. The names are yours to choose.
    • Looping and changing. Writing to result while looping over d is fine, because they are two different maps. Changing the map you are looping over would be a mistake.
    • Names inside the loop. value here is an ordinary variable name, not a keyword.

    Tracing the loop

    For {a=b, b=c}, the new map after each entry is:

    a=b -> {b=a}
    b=c -> {b=a, c=b}

    The first entry creates the key b in the new map. The second entry has b as its old key, but in the new map the old key becomes a value, so nothing clashes with the key b created a moment ago.

    Edge cases and common mistakes

    • One entry. {cat=dog} gives {dog=cat}.
    • Repeated values. The lesson promises that all values are different. If two keys shared a value, they would write to the same new key and the later one would win: {a=x, b=x} gives {x=b}, with one entry fewer than the input.
    • Writing result[key] = value. That copies the map instead of inverting it.
    • Looking up by value. A map finds a value by its key quickly, but not the other way round. Inverting once makes lookups by the old values fast.

    Why invert a map

    A map looks up a value by its key, never a key by its value. When you need the second question often, build the inverted map once. After that, the old values become the keys, and the lookup is as fast as the first one.

    Testing

    • {apple=red, banana=yellow, plum=purple} gives {red=apple, yellow=banana, purple=plum}.
    • {cat=dog} gives {dog=cat}.
    • {a=b, b=c} gives {b=a, c=b}.
    • {a=x, b=x} gives {x=b} (not allowed by the lesson, but it shows what happens).
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free