Problem overview
The function safeLookup receives an unordered_map<string, int> called scores and a name. It returns the score of name, or 0 when name isn't a key of scores.
With {"Ana": 90, "Ben": 75, "Cara": 88}, the name "Ben" gives 75 and the name "Dan" gives 0. An empty map gives 0 for any name. Names must match exactly, so "ana" is not "Ana" and also gives 0.
Approach
Reading scores[name] works for a name that is present, but for a missing one it quietly inserts name with the value 0. That happens to equal the wanted answer here, but it also changes the map: after looking up "Dan" that way, the three-entry map above has four entries. A safe lookup should leave the map alone.
So the function first asks whether the key exists. scores.count(name) returns how many entries have that key. A map holds each key at most once, so the answer is 1 when the key is there and 0 when it isn't. If it is there, return its score. Otherwise fall through to return 0.
Step by step
- Check the key. Write an
ifwhose condition isscores.count(name) > 0, and inside it returnscores[name]. Here the brackets are safe, because the key is known to exist. - Return 0 after the
if. The code reaches this line only when the name is missing, since a present name has already returned inside theif.
The solution in C++
class Solution {
public:
int safeLookup(unordered_map<string, int>& scores, string name) {
if (scores.count(name) > 0) {
return scores[name];
}
return 0;
}
};
Notes on the C++ details:
- The map keeps its size. On the three-entry map, lookups of
"Ben","Dan"and"ana"return 75, 0 and 0, and the map still has 3 entries afterwards. A plainscores["Dan"]would return 0 as well, but leave the map with 4 entries. countversusfind.find(name)returns an iterator, equal toscores.end()when the key is missing. It lets you check and read with one search instead of two.countis shorter for a plain yes/no question, and the lesson uses it.- The return type is
int. A missing score is reported as 0 because every real score is between 0 and 100. A real score of 0 and a missing name therefore look the same to the caller.
Edge cases and common mistakes
- An empty map.
countgives 0, so the function returns 0 and the map stays empty. - Different case. Keys are compared character by character, so
"ana"doesn't match"Ana". - Returning inside the
ifonly. Without the finalreturn 0, a missing name makes the function end without returning a value, which is undefined behaviour in C++. - Testing
scores[name]instead ofcount. A check likeif (scores[name])can't tell a missing key from a real score of 0, and it inserts the key when it is missing.
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.
