Start learning free

LESSON 133 OF 291 · DICTIONARIES - CHALLENGES

Safe Lookup in Kotlin: getOrDefault on a Map

Practice Read the full explanation

Given a HashMap scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · DICTIONARIES - CHALLENGES

    Safe Lookup in Kotlin, explained

    Problem overview

    The function safeLookup receives scores, a map from names to scores, and a name. It returns the score of that name, or 0 when the name isn't a key. The map can be empty, and keys must match exactly, upper and lower case included.

    With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and "Dan" gives 0. With an empty map, "Ana" gives 0. The name "ana" also gives 0 on the first map, since it is not spelled like "Ana".

    Approach

    Reading a map with brackets, scores[name], gives an Int?: the score, or null for a missing key. Printing scores["Dan"] shows null. This function must return a plain Int, so the missing case needs a replacement value.

    The map method getOrDefault does it in one call: the first argument is the key, the second is what to return when the key is absent.

    Step by step

    1. Call getOrDefault(name, 0) on scores and return the result. It gives the stored score when the key exists and 0 otherwise.

    The solution in Kotlin

    class Solution {
        fun safeLookup(scores: MutableMap<String, Int>, name: String): Int {
            return scores.getOrDefault(name, 0)
        }
    }
    

    Some details worth knowing:

    • The result is a plain Int. Unlike the bracket read, getOrDefault never gives null here, so no !! is needed.
    • The map isn't changed. getOrDefault only reads. After looking up "Dan" the map still has 3 entries.
    • The Elvis operator is another way. scores[name] ?: 0 means "the value, or 0 if it is null", and gives the same results on this lesson's inputs. Use getOrDefault here, as the lesson does.
    • A stored 0 is not a missing key. Scores can be 0. getOrDefault returns the stored value for a present key, so a real 0 and the default 0 look the same to the caller, which is what the task wants.

    Other ways to get a default

    There are other ways to write the same lookup. scores.getOrElse("Dan") { 0 } takes a small block that runs only when the key is missing, which helps when the default is costly to compute. An if with containsKey first asks whether the key exists, then reads it:

    val scores = mutableMapOf("Ana" to 90)
    val score = if (scores.containsKey("Ana")) scores["Ana"]!! else 0
    println(score) // 90
    

    That is longer than getOrDefault and looks the key up twice, so the single call is the better fit for this task.

    Complexity

    Time is O(1) on average, because a hash map finds a key, or finds that it is absent, without scanning every entry. Space is O(1) extra: the function creates nothing.

    Why a default beats a null check

    Returning 0 for a name with no score means the caller never has to handle null. The decision about missing keys is made once, inside the lookup, and every caller gets an Int it can add or compare right away.

    Edge cases and common mistakes

    • Using !!. scores[name]!! throws a NullPointerException for a missing name, and this lesson's tests include missing names.
    • Different case. Keys are compared exactly, so "ana" doesn't match "Ana" and the answer is 0.
    • Empty map. There are no keys, so every name gets the default.

    Testing

    • {"Ana": 90, "Ben": 75, "Cara": 88} with "Ben" gives 75.
    • The same map with "Dan" gives 0.
    • The same map with "ana" gives 0.
    • {} with "Ana" gives 0.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free