Start learning free

LESSON 131 OF 291 · DICTIONARIES - CHALLENGES

Phone Book Lookup in Scala: Reading a mutable.Map

Practice Read the full explanation

Given a phone book phoneBook, a mutable.Map from names to phone numbers, and a name, return the phone number of name.

Every name in the phone book is a key, and its value is that person's phone number, a string like "555-0142". The name you look up is always in the phone book.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}, name = "Ben"
Output: "555-0199"
Explanation: The key "Ben" maps to "555-0199".

Example 2:

Input: phoneBook = {"Max": "555-0100"}, name = "Max"
Output: "555-0100"
Explanation: The phone book has a single entry, and it is the one we look up.

Example 3:

Input: phoneBook = {"Tom": "555-0111", "Tim": "555-0111"}, name = "Tim"
Output: "555-0111"
Explanation: Tom and Tim share a phone number. We only need the value of the key "Tim".

 

Constraints:

  • phoneBook has at least one entry.
  • name is always a key of phoneBook.
  • Names are single words made of English letters, and they are all different. Two people can share a phone number.
  • Every phone number is a string of three digits, a dash and four digits, like "555-0142".
STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · DICTIONARIES - CHALLENGES

    Phone Book Lookup in Scala, explained

    Problem overview

    The method phoneBookLookup gets phoneBook, a scala.collection.mutable.Map[String, String] from names to phone numbers, and a name. It returns the phone number stored for that name. The name is always a key of the map.

    For {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"} and name = "Ben", the answer is "555-0199". Two people can share a number, which doesn't matter: the lookup goes by key, and keys are all different.

    Approach

    A map stores key-value pairs and finds a value from its key directly, without scanning the entries. In Scala you read a value by writing the key in parentheses after the map: phoneBook(name). That is a call to the map's apply method.

    Step by step

    There is only one step: return phoneBook(name). Write name without quotes. It is a variable holding the key. phoneBook("name") would look for a person called "name".

    The solution in Scala

    class Solution {
        def phoneBookLookup(phoneBook: scala.collection.mutable.Map[String, String], name: String): String = {
            return phoneBook(name)
        }
    }
    

    The parameter type is written with its full package path, scala.collection.mutable.Map. Plain Map in Scala means the immutable one, so the long name makes clear which kind the lesson uses. Reading works the same on both.

    Keys are unique, values can repeat

    A map holds at most one value per key. Writing phoneBook("Ben") = "555-0000" on a book that already has Ben replaces his number, and the map still has the same number of entries. Different keys may hold the same value: in {"Tom": "555-0111", "Tim": "555-0111"}, phoneBook("Tom") and phoneBook("Tim") are equal strings, and each lookup still answers for its own key. That is the situation of the lesson's third example.

    Edge cases and common mistakes

    • A missing key throws. Reading phoneBook("Zed"), when "Zed" isn't a key, throws NoSuchElementException: key not found: Zed. This lesson promises that the name is present, so the plain lookup is safe here.
    • When a key might be absent, use get, which returns an Option. For the map above, phoneBook.get("Ben") gives Some(555-0199) and phoneBook.get("Zed") gives None. Use getOrElse(key, default) to get a plain value instead.
    • Spelling counts. Keys are strings compared by value, so "ben" is not "Ben".

    Why a map and not a list

    A phone book could be stored as a list of name and number pairs, but finding one name would mean walking the list from the start. A map is built for this question: given a key, give me its value. That is why the lesson stores the book as a map, and why the lookup is a single short expression.

    Checking for a key first

    When you aren't sure a key is there, contains asks without throwing. With the map {"Ana": "555-0142", "Ben": "555-0199"}, phoneBook.contains("Ben") is true and phoneBook.contains("Zed") is false. A lookup is then safe after a true. Mutable and immutable maps read the same way: Map("Ana" -> "555-0142", "Ben" -> "555-0199")("Ben") also gives 555-0199.

    Here the lesson already promises the key exists, so the single expression phoneBook(name) is all the method needs. The last expression of a block is its value in Scala, so return could be left out, but the lesson's code writes it explicitly, and so does the solution above.

    Testing

    phoneBookLookup({"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}, "Ben")  -> 555-0199
    phoneBookLookup({"Tom": "555-0111", "Tim": "555-0111"}, "Tim")                      -> 555-0111
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free