Problem overview
The method countVote gets votes, an unordered_map<string, int> from names to vote counts, and the name on a new vote. The person called name gets one more vote, and the method returns votes. A name that has no votes yet is not in the map, so it starts from 0 and ends with 1. The order of entries does not matter.
With {"Ana": 3, "Ben": 5} and "Ana", Ana goes to 4. With "Cara", a new key appears with 1. With an empty map and "Max", the result is {"Max": 1}.
Approach
This is the "default, then check" pattern. Start with a count of 0, then read the real count only if the name is a key. Whatever the count is, store count + 1 under the name. For a new name that adds the key, and for an existing one it replaces the old number with the new one.
Step by step
- Create
int count = 0;. It will hold the votes the person has so far. - Write an
ifwhose condition isvotes.count(name) > 0. Inside it, setcounttovotes[name]. The check keeps the map unchanged for a missing name. - After the
if, storecount + 1under the key:votes[name] = count + 1;. - Return
votes. Only the entry ofnamechanged.
The solution in C++
class Solution {
public:
unordered_map<string, int> countVote(unordered_map<string, int>& votes, string name) {
int count = 0;
if (votes.count(name) > 0) {
count = votes[name];
}
votes[name] = count + 1;
return votes;
}
};
Running the method on the statement's examples, with entries printed as name: count lines sorted by name, gives:
Ana: 4
Ben: 5
For "Cara" the map becomes Ana: 3, Ben: 5, Cara: 1. For the empty map and "Max" it becomes Max: 1.
Another way
For an unordered_map<string, int>, a missing key read with [] is created with 0, so votes[name]++ does the whole job in one line. Applied twice to the key "x" of an empty map, it gives x: 2. The lesson's version spells out each step, which is clearer while you are learning how maps behave. Both give the same results.
Trying more inputs
Start with an empty map and count three votes for "Ana" and one for "Bo". The first call creates Ana with 1, the next two raise her to 3, and Bo is created with 1. The final map is Ana: 3 and Bo: 1. Each call is independent: it needs only the current map and the name.
The same method also works if the map already holds many names, since only one key is looked up and changed each time.
Complexity
Time is O(1) on average and space is O(1) extra, because each step is one hash-map lookup or store.
Edge cases and common mistakes
- Forgetting the first vote. Storing the new name with 0 instead of 1 loses the vote. The expression is
count + 1, andcountis 0 for a new name. - Putting the store inside the if. Then new names are never added. The store must come after the
if. - Returning a different value. The method returns the whole map, not the new count.
- Empty map. It needs no special case, because
count(name)is 0 and the store creates the entry.
