Problem overview
The method sellItem gets inventory, an unordered_map<string, int> from item names to how many of each a shop has, and the item that was just bought. It sells one: the count of item drops by 1, and when it reaches 0, the item is removed from the map. It returns the updated map, and the order of entries does not matter.
With {"apples": 5, "pears": 2} and "apples", the apples go to 4. With {"cups": 1, "plates": 3} and "cups", the last cup is sold, so "cups" is erased and only plates remain. With {"pen": 1} and "pen", the result is an empty map.
Approach
The constraints promise that item is always a key and every count is at least 1. So reading the count is safe, and subtracting 1 never gives a negative number. First work out what is left. Then, if it is 0, erase the key. Otherwise, store the smaller count.
Step by step
- Compute
int remaining = inventory[item] - 1;. The key exists, so[]reads the real count without adding anything. - If
remaining == 0, callinventory.erase(item). A sold-out item leaves the map, key and value both. - In the
elsebranch, storeremainingunder the key:inventory[item] = remaining. - Return
inventory. Only the entry ofitemchanged or went away; every other entry is as it was.
The solution in C++
class Solution {
public:
unordered_map<string, int> sellItem(unordered_map<string, int>& inventory, string item) {
int remaining = inventory[item] - 1;
if (remaining == 0) {
inventory.erase(item);
} else {
inventory[item] = remaining;
}
return inventory;
}
};
Running the method on the statement's examples, with entries printed as item: count lines sorted by item name, gives:
apples: 4
pears: 2
Then plates: 3 alone for the cups example, and nothing at all for the pen example, because the map is empty.
Trying more inputs
Start with {"apples": 2} and sell apples twice. After the first sale the count is 1 and the map still has one entry. After the second sale the map has no entries, and count("apples") is 0. This shows both branches in a row: the count is stored while some are left, and the key is erased at the end.
Try the sale on the item with the largest count too: selling one apple from five always leaves four and never touches the pears. The method works on one key only, so the other entries cannot be affected.
Complexity
Time is O(1) on average, since each lookup, store and erase takes constant time in a hash map. Space is O(1) extra.
Edge cases and common mistakes
- Storing 0 instead of erasing. Setting the count to 0 leaves
"cups": 0in the map, but the lesson wants the key gone. - Erasing too early. Erase only when the remaining count is 0, not when the old count is above 0.
- Using [] on a missing key. The constraints rule it out, but it is worth knowing what happens:
inventory[item]would add the key with 0, and the subtraction would store -1. For an item not in{"a": 1}, the result would containzzz: -1. - Forgetting the else. Without it, the code would store 0 after erasing and bring the key back.
