Start learning free

LESSON 135 OF 677 · DICTIONARIES - CHALLENGES

Add a Contact to a Map in Kotlin Without Overwriting

Practice Read the full explanation

You get a phone book phoneBook, a HashMap from names to phone numbers. You also get a name and a phone number.

Add name with its number to the phone book, and return the phone book.

Only add name when it isn't in the phone book yet. A name that is already there keeps its old number. The order of the entries doesn't matter.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199"}, name = "Cara", number = "555-0123"
Output: {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}
Explanation: "Cara" isn't in the phone book yet, so she is added.

Example 2:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199"}, name = "Ben", number = "555-0100"
Output: {"Ana": "555-0142", "Ben": "555-0199"}
Explanation: "Ben" is already in the phone book. He keeps his old number, "555-0199".

Example 3:

Input: phoneBook = {}, name = "Max", number = "555-0100"
Output: {"Max": "555-0100"}
Explanation: The phone book was empty. Now it has one contact.

 

Constraints:

  • phoneBook can be empty.
  • Names are single words made of English letters.
  • Every phone number has three digits, a dash and four digits, like "555-0142".
  • Two people can share a phone number.
STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · DICTIONARIES - CHALLENGES

    Add Contact in Kotlin, explained

    Problem overview

    The function addContact gets a phone book, a MutableMap<String, String> from names to phone numbers, plus a name and a number. It adds the name with its number and returns the phone book, but only when the name isn't a key yet. A name that is already there keeps its old number. The order of the entries doesn't matter, and the phone book can start empty.

    With {"Ana": "555-0142", "Ben": "555-0199"} and the new name "Cara", she is added. With "Ben" and a different number, the book stays as it was and Ben keeps "555-0199". With an empty phone book and "Max", the book ends up with one contact.

    Approach

    Assigning to a map key with phoneBook[name] = number adds the key when it is new and replaces the value when it already exists. That second part is what this task forbids, so the assignment must run only when name isn't a key. The test for that is name !in phoneBook, where in asks the map whether the name is one of its keys, and !in asks the opposite.

    Step by step

    1. Test for a new name. Write an if whose condition is name !in phoneBook, with its closing brace right away.
    2. Add the contact inside it. phoneBook[name] = number adds the key and its value. Because it only runs for a new name, no old number can be overwritten.
    3. Return phoneBook after the if. Either the new contact is in, or the book is unchanged.

    The solution in Kotlin

    class Solution {
        fun addContact(phoneBook: MutableMap<String, String>, name: String, number: String): MutableMap<String, String> {
            if (name !in phoneBook) {
                phoneBook[name] = number
            }
            return phoneBook
        }
    }
    

    Printing each result as key: value lines sorted by key (the format the tests use) gives, for the three examples:

    Ana: 555-0142
    Ben: 555-0199
    Cara: 555-0123
    
    Ana: 555-0142
    Ben: 555-0199
    
    Max: 555-0100
    

    The function changes the map it receives and returns that same map. A MutableMap parameter is fine to change even though parameters themselves can't be reassigned.

    Edge cases and common mistakes

    • Assigning without the check. phoneBook[name] = number on its own turns the second example into {Ben=555-0100} for Ben: the old number is lost, because assigning to an existing key replaces its value.
    • Checking the number instead of the name. Two people can share a phone number, so only the name decides whether to add.
    • Reversed condition. With name in phoneBook the code would only touch names that already exist.
    • Empty phone book. No key is there, so the name is added. No special case is needed.
    • Case. Keys match exactly, so "ben" and "Ben" are different names.

    Another way

    Maps have a method for exactly this job: putIfAbsent(name, number) adds the pair only when the key is missing and leaves an existing key alone. On the first two examples it gives the same books as the if version: Cara is added, and Ben keeps "555-0199". The lesson's steps use the explicit if with !in, which shows the check you would write for other rules too, such as "add only when the number is valid".

    Testing

    • Ana and Ben, adding Cara with "555-0123", gives Ana, Ben and Cara.
    • Ana and Ben, adding Ben with "555-0100", leaves Ben at "555-0199".
    • An empty book, adding Max with "555-0100", gives only Max.
    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free