Start learning free

LESSON 132 OF 667 · DICTIONARIES - CHALLENGES

Sell an Item: Decrement or Erase in a C++ Map

Practice Read the full explanation

You get inventory, an unordered_map from item names to how many of each item a shop has. You also get the item a customer just bought.

Sell one item and return the updated dictionary.

The count of item drops by 1. When it reaches 0, remove item from the dictionary. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "pears": 2}, item = "apples"
Output: {"apples": 4, "pears": 2}
Explanation: One apple is sold, so 5 - 1 = 4 apples are left.

Example 2:

Input: inventory = {"cups": 1, "plates": 3}, item = "cups"
Output: {"plates": 3}
Explanation: The last cup is sold. No cups are left, so "cups" is removed.

Example 3:

Input: inventory = {"pen": 1}, item = "pen"
Output: {}
Explanation: The only pen is sold. Nothing is left in the shop.

 

Constraints:

  • item is always a key of inventory.
  • Every count is at least 1.
  • Item names are single lowercase words.
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · DICTIONARIES - CHALLENGES

    Sell An Item in C++, explained

    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

    1. Compute int remaining = inventory[item] - 1;. The key exists, so [] reads the real count without adding anything.
    2. If remaining == 0, call inventory.erase(item). A sold-out item leaves the map, key and value both.
    3. In the else branch, store remaining under the key: inventory[item] = remaining.
    4. Return inventory. Only the entry of item changed 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": 0 in 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 contain zzz: -1.
    • Forgetting the else. Without it, the code would store 0 after erasing and bring the key back.
    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free