Start learning free

LESSON 132 OF 285 · DICTIONARIES - CHALLENGES

Restock in Go: Updating a Map Entry with +=

Practice Read the full explanation

A shop keeps its stock in inventory, a map from item names to how many of each item it has. A delivery brings amount more of item. Add amount to the count of item and return the updated dictionary.

Only the count of item changes: every other entry stays as it is. The order of the entries doesn't matter.

 

Example 1:

Input: inventory = {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas", amount = 3
Output: {"apples": 5, "bananas": 5, "cherries": 10}
Explanation: "bananas" had a count of 2, and 2 + 3 = 5. The apples and the cherries keep their counts.

Example 2:

Input: inventory = {"milk": 0}, item = "milk", amount = 12
Output: {"milk": 12}
Explanation: A count of 0 means the milk was sold out. The delivery brings it to 0 + 12 = 12.

Example 3:

Input: inventory = {"pens": 7, "paper": 3}, item = "pens", amount = 1
Output: {"pens": 8, "paper": 3}
Explanation: One more pen: 7 + 1 = 8.

 

Constraints:

  • item is always a key of inventory.
  • amount is at least 1.
  • Every count is 0 or more.
  • Item names are single lowercase words, and they are all different.
STEP 1 OF 2
    Ctrl + Enter to check

    GO · DICTIONARIES - CHALLENGES

    Restock in Go, explained

    Problem overview

    The function restock receives inventory, a map[string]int from item names to counts, an item that is always one of its keys, and an amount to add. It adds amount to the count of item and returns the updated map. Every other entry stays as it was.

    For {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the count of bananas goes from 2 to 5 and the other two stay put. A count of 0 works the same way: {"milk": 0} with amount = 12 becomes {"milk": 12}.

    Approach

    In Go, inventory[item] can stand on the left side of an assignment as well as be read. So inventory[item] += amount reads the old count, adds amount and stores the sum under the same key. Then return the map.

    Step by step

    1. Add the amount. Use += on inventory[item]: the old count is read, amount is added, and the sum is stored back under the same key.
    2. Return inventory. The change is already in it, so every entry comes back, with only the count of item different.

    The solution in Go

    func restock(inventory map[string]int, item string, amount int) map[string]int {
        inventory[item] += amount
        return inventory
    }
    

    Details worth knowing:

    • Maps are not copied when passed. The function changes the caller's map. After r := restock(inv, "bananas", 3), both r and inv print map[apples:5 bananas:5 cherries:10], because they are the same map. The function returns the map for convenience, not because it made a new one.
    • A missing key starts from zero. Reading a key that isn't in a map of int gives 0, so += on a new key creates it with the amount: from {"kiwis": 1}, inv["plums"] += 4 gives map[kiwis:1 plums:4]. The lesson's item is always present, so this only matters if you reuse the idea.
    • Printing order. Iterating over a map visits keys in random order, but fmt.Println prints maps with the keys sorted. The lesson doesn't care about entry order either.

    The same idea with other operators

    Any assignment operator works on a map entry. ++ and -- do too, so counting with a map is a one-liner: with counts := map[string]int{}, running counts["a"]++ twice leaves map[a:2]. A delivery is +=; a sale would be -=, and Go would let the count go below zero, so a real shop would check the stock first. This lesson only adds, and its counts are never negative.

    Because the map is shared, there are two ways to use the function. You can ignore the returned value and read the map you passed in, or use the returned map. Both show the same entries. If you needed the old map unchanged, you would have to copy it into a new map first, with a loop, since assigning a map to another variable copies nothing but the reference.

    Edge cases and common mistakes

    • Assigning instead of adding. inventory[item] = amount replaces the count. For the bananas that gives 3 instead of 5.
    • Quoting the key. inventory["item"] uses the word item, not the variable.
    • Forgetting the return. The function has a result type, so a missing return is a compile error.

    Testing

    • {"apples": 5, "bananas": 2, "cherries": 10}, "bananas", 3 gives map[apples:5 bananas:5 cherries:10].
    • {"milk": 0}, "milk", 12 gives map[milk:12].
    • {"pens": 7, "paper": 3}, "pens", 1 gives map[paper:3 pens:8].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free