Start learning free

LESSON 130 OF 667 · DICTIONARIES - CHALLENGES

Safe Lookup in C++: Checking a Key With count

Practice Read the full explanation

Given an unordered_map 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 2
    Ctrl + Enter to check

    C++ · DICTIONARIES - CHALLENGES

    Safe Lookup in C++, explained

    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

    1. Check the key. Write an if whose condition is scores.count(name) > 0, and inside it return scores[name]. Here the brackets are safe, because the key is known to exist.
    2. Return 0 after the if. The code reaches this line only when the name is missing, since a present name has already returned inside the if.

    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 plain scores["Dan"] would return 0 as well, but leave the map with 4 entries.
    • count versus find. find(name) returns an iterator, equal to scores.end() when the key is missing. It lets you check and read with one search instead of two. count is 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. count gives 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 if only. Without the final return 0, a missing name makes the function end without returning a value, which is undefined behaviour in C++.
    • Testing scores[name] instead of count. A check like if (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.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free