Start learning free

LESSON 135 OF 674 · DICTIONARIES - CHALLENGES

Sell an Item in C#: Updating or Removing a Dictionary Count

Practice Read the full explanation

You get inventory, a Dictionary 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 receives inventory, a Dictionary<string, int> from item names to how many of each item a shop has, and the item a customer just bought. It sells one: the count of item drops by 1, and when it reaches 0 the item is removed from the dictionary. It returns the updated dictionary. The order of the entries does not matter.

    With 5 apples and 2 pears, selling an apple leaves 4 apples. With 1 cup and 3 plates, selling a cup takes the last cup, so "cups" is removed and only the plates are left. With a single pen, selling it leaves an empty dictionary. The constraints promise that item is always a key and that every count is at least 1.

    Approach

    Work out the count after the sale first: the current count minus 1. Then there are two cases. If nothing remains, the item is sold out, and a shop does not list items it has none of, so the key must go. Otherwise the item stays, and its key gets the new, smaller count.

    Deleting is the key point. Storing 0 would leave "pen" in the dictionary with a count of 0, which is not what the task asks for. Use Remove, which deletes the key and its value together.

    Step by step

    1. Compute remaining. inventory[item] - 1, in an int. Reading the key is safe because it always exists.
    2. Handle a sold-out item. An if that checks whether remaining is 0, with inventory.Remove(item) in its body.
    3. Handle the rest. An else branch stores remaining under the key: inventory[item] = remaining.
    4. Return inventory after the else branch. Every other entry is untouched.

    The solution in C#

    class Solution {
        public Dictionary<string, int> SellItem(Dictionary<string, int> inventory, string item) {
            int remaining = inventory[item] - 1;
            if (remaining == 0) {
                inventory.Remove(item);
            } else {
                inventory[item] = remaining;
            }
            return inventory;
        }
    }
    

    On the three examples it returns these dictionaries, in the lesson's output form of key: value lines sorted by key (the last one is empty and prints no lines):

    apples: 4
    pears: 2
    
    plates: 3
    

    The C# details worth knowing:

    • Reading a missing key throws. inventory[item] throws a KeyNotFoundException when the key is absent. The lesson guarantees it is present. If you called SellItem with "ink" on a dictionary that has only pens, you would get that exception.
    • The index setter changes the value. The assignment inventory[item] = remaining replaces the old count of an existing key.
    • Remove takes the key. It returns a bool, which this code ignores because the key is known to be there.
    • The dictionary is changed in place. It is a reference type, so the caller's dictionary is the one that changes, and the method returns the same object.

    Edge cases and common mistakes

    • Selling the last one. The key must disappear. After storing 0 instead, the dictionary would still have one entry, and the printed result would show pen: 0.
    • Removing too early. Calling Remove every time loses the item even when stock is left.
    • Checking remaining after storing it. Compute the number first and then decide. The count is read only once.
    • Other items. They are never touched: only the sold item's entry changes.
    • Dropping the else. If the store runs after the Remove, it puts the key back with a count of 0.

    Testing

    • {"apples": 5, "pears": 2}, "apples" gives {"apples": 4, "pears": 2}.
    • {"cups": 1, "plates": 3}, "cups" gives {"plates": 3}.
    • {"pen": 1}, "pen" gives {}.
    • {"pen": 2}, "pen" gives {"pen": 1}.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free