Start learning free

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

Invert a Dictionary in Scala: Swapping Keys and Values

Practice Read the full explanation

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

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Invert A Dictionary in Scala, explained

    Problem overview

    The method invertDictionary receives a mutable.Map[String, String] named d and returns a new mutable.Map[String, String] 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 no two entries collide.

    For mutable.Map("apple" -> "red", "banana" -> "yellow", "plum" -> "purple") the result is HashMap(red -> apple, yellow -> banana, purple -> plum). A tricky case is mutable.Map("a" -> "b", "b" -> "c"): the word b is a value and a key. Inverting the entry a -> b gives b -> a, and inverting b -> c gives c -> b, so the result is HashMap(b -> a, c -> b). Both entries land on different keys, so nothing is lost.

    Approach

    Build a new map and read from the old one. Each entry turns around on its own, without looking at any other entry, so a single pass over d is enough. Writing into a separate map also means d is never changed while the loop reads it.

    Think of it as turning a lookup table around. The original answers "which color is this fruit?", and the inverted one answers "which fruit has this color?". That only works as a table if each color belongs to exactly one fruit, which is what the all-different-values rule guarantees.

    Step by step

    1. Create the result. mutable.Map[String, String]() in a val named result. The lesson's file already imports scala.collection.mutable, so mutable.Map is the changeable map.
    2. Loop over the entries. for ((key, value) <- d) goes through d one entry at a time, and the parentheses before <- split each entry into its key and value.
    3. Store the swapped pair. result(value) = key makes the old value the new key.
    4. Return result.

    The solution in Scala

    class Solution {
        def invertDictionary(d: mutable.Map[String, String]): mutable.Map[String, String] = {
            val result = mutable.Map[String, String]()
            for ((key, value) <- d) {
                result(value) = key
            }
            return result
        }
    }
    
    • Destructuring an entry. A map's elements are pairs, (key, value) tuples. The pattern (key, value) in the generator takes each pair apart and gives you two names to use.
    • Naming and the import. The lesson's file already has the import that makes mutable.Map work. In a file of your own, add import scala.collection.mutable at the top.
    • Writing to a key adds or replaces. result(value) = key creates the entry when the key is new.
    • The input is untouched. The loop only reads d. After the call, d still holds the original entries.
    • A shorter form. d.map((k, v) => (v, k)) builds the inverted map in one expression. On a mutable map it returns a mutable map, and the loop above spells out what it does.

    Reading the swap

    In result(value) = key, the names are easy to mix up, so say it aloud: "in the result, the old value points to the old key". For the entry banana -> yellow the loop sees key = "banana" and value = "yellow", and stores yellow -> banana.

    Edge cases and common mistakes

    • Repeated values. The lesson promises all values differ. If two keys shared a value, the later entry would overwrite the earlier, and the result would be smaller than d. For mutable.Map("x" -> "same", "y" -> "same") the result has one entry, HashMap(same -> y).
    • Swapping the wrong way. result(key) = value just copies the map. The key of the new entry must be the old value.
    • One entry. mutable.Map("cat" -> "dog") gives HashMap(dog -> cat).

    Testing

    • mutable.Map("apple" -> "red", "banana" -> "yellow", "plum" -> "purple") gives HashMap(red -> apple, yellow -> banana, purple -> plum).
    • mutable.Map("cat" -> "dog") gives HashMap(dog -> cat).
    • mutable.Map("a" -> "b", "b" -> "c") gives HashMap(b -> a, c -> b).
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free