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
- Call
getOrDefault(name, 0)onscoresand 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,getOrDefaultnever givesnullhere, so no!!is needed. - The map isn't changed.
getOrDefaultonly reads. After looking up"Dan"the map still has 3 entries. - The Elvis operator is another way.
scores[name] ?: 0means "the value, or 0 if it isnull", and gives the same results on this lesson's inputs. UsegetOrDefaulthere, as the lesson does. - A stored 0 is not a missing key. Scores can be 0.
getOrDefaultreturns 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 aNullPointerExceptionfor 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"gives75.- The same map with
"Dan"gives0. - The same map with
"ana"gives0. {}with"Ana"gives0.
