Start learning free

LESSON 133 OF 671 · DICTIONARIES - CHALLENGES

Sell an Item in Java: Updating a HashMap Count

Practice Read the full explanation

You get inventory, a HashMap 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

    JAVA · DICTIONARIES - CHALLENGES

    Sell An Item in Java, explained

    Problem overview

    The method sellItem receives inventory, a HashMap from item names to how many the 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 map entirely. It returns the updated map. The item is always a key of inventory, every count is at least 1, and the order of entries does not matter.

    With apples 5 and pears 2, selling an apple leaves apples 4. With cups 1, selling a cup removes the key cups, so only plates remains. Selling the only pen gives an empty map.

    Approach

    There are two outcomes. If the new count is still above 0, store it back with put, which replaces the old value. If the new count is 0, the item is sold out and the entry is deleted with remove. So the plan is: compute the count after the sale, then branch on whether it is 0.

    Reading the count with get is safe here, because the statement guarantees the item exists. Without that guarantee, get would return null for a missing key and the subtraction would throw a NullPointerException.

    Step by step

    1. Compute what is left: int remaining = inventory.get(item) - 1;. The value from get is an Integer, which Java unboxes to do the subtraction.
    2. If remaining is 0, sold out: inventory.remove(item) deletes the key and its value together.
    3. Otherwise put the item back with remaining. Putting a key that already exists replaces its value.
    4. Return inventory. Only the sold item's entry changed.

    The solution in Java

    class Solution {
        public HashMap<String, Integer> sellItem(HashMap<String, Integer> inventory, String item) {
            int remaining = inventory.get(item) - 1;
            if (remaining == 0) {
                inventory.remove(item);
            } else {
                inventory.put(item, remaining);
            }
            return inventory;
        }
    }
    

    Details worth knowing:

    • On a HashMap, remove takes a key, never an index.
    • The map is changed in place, and the same map is returned.
    • Storing the count in remaining avoids calling get twice and gives the number a meaningful name.

    Edge cases and common mistakes

    • Leaving a zero behind. Always doing put(item, remaining) would leave cups in the map with a count of 0. The task wants the key gone.
    • Removing too early. Testing the old count against 0 instead of the new one never fires, because every count starts at 1 or more.
    • Forgetting to return. The method has to return the map, even though it changed the original in place.
    • Missing item. Not part of the tests, but selling an item that is not a key would fail on the subtraction with a NullPointerException.

    Why remove instead of keeping a zero

    A map that keeps cups: 0 still answers containsKey("cups") with true and still counts the key in size(). After put("cups", 0) on the cups example, the map has 2 keys and get("cups") is 0. Removing the key makes "sold out" and "never stocked" look the same, which is what the task wants.

    Testing

    Results, printed as key: value lines sorted by key, as the lesson's tests print them:

    • apples 5, pears 2, selling apples gives apples: 4, pears: 2.
    • cups 1, plates 3, selling cups gives plates: 3.
    • pen 1, selling pen gives an empty map.
    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free