Start learning free

LESSON 132 OF 291 · DICTIONARIES - CHALLENGES

Restock in Scala: Updating a Value in a mutable.Map

Practice Read the full explanation

A shop keeps its stock in inventory, a mutable.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

    SCALA · DICTIONARIES - CHALLENGES

    Restock in Scala, explained

    Problem overview

    The method restock gets inventory, a scala.collection.mutable.Map[String, Int] from item names to counts, an item that is always a key, and an amount that arrived in a delivery. It adds amount to the count of item and returns the updated map. Every other entry stays the same.

    For {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the count of bananas goes from 2 to 5. The result holds apples 5, bananas 5 and cherries 10. The order of the entries doesn't matter.

    Approach

    The new count is the old count plus amount. A mutable map can be changed in place, so the method reads the old count, adds, and writes the sum back under the same key. Then it returns the same map.

    Step by step

    1. Set inventory(item) to inventory(item) + amount. The right side is evaluated first, so it still sees the old count. Then the assignment replaces the value stored under item.
    2. Return inventory. It was changed in place, so it already holds the new count and all the untouched entries.

    The solution in Scala

    class Solution {
        def restock(inventory: scala.collection.mutable.Map[String, Int], item: String, amount: Int): scala.collection.mutable.Map[String, Int] = {
            inventory(item) = inventory(item) + amount
            return inventory
        }
    }
    

    Language details:

    • inventory(item) = value is shorthand for calling the map's update method. It only works on a mutable map. An immutable Map has no update, so the line wouldn't compile.
    • inventory(item) on the right side calls apply, which throws if the key is missing. The lesson guarantees that item is a key.
    • The map is changed in place. The caller's map and the returned map are the same object, so there is no copy.

    Edge cases and common mistakes

    • A count of zero. With {"milk": 0}, item = "milk" and amount = 12, the count becomes 12.
    • Replacing instead of adding. Writing inventory(item) = amount throws away the old count. For bananas it would give 3, not 5.
    • Changing other entries. Only one key is assigned, so nothing else changes.
    • If the key could be new, use inventory.getOrElse(item, 0) + amount on the right side. The lesson doesn't need it, because item is always present.

    Reading and writing in one line

    The line inventory(item) = inventory(item) + amount looks like it uses inventory(item) twice in two different roles, and it does. On the right it is a read, a call to apply. On the left it is a write, a call to update. The same pattern, "new value from old value", appears for counters, running totals and scores, wherever a map holds numbers that change over time. The augmented form inventory(item) += amount would also compile for a mutable map and means the same thing, but the lesson's longer form shows each part.

    A new key and an immutable map

    Assigning to a key that isn't there adds it. Starting from {"apples": 5}, the line inventory("pears") = inventory.getOrElse("pears", 0) + 4 leaves apples 5 and pears 4. The plain inventory("pears") on the right side would have thrown, so getOrElse supplies the starting 0.

    With an immutable map the idea is the same, but the update returns a new map. For im = Map("apples" -> 5), im.updated("apples", im("apples") + 3) gives Map(apples -> 8), and im itself is still Map(apples -> 5). This lesson uses the mutable version, so the same object changes and is returned.

    Testing

    restock({"apples": 5, "bananas": 2, "cherries": 10}, "bananas", 3)  -> apples 5, bananas 5, cherries 10
    restock({"milk": 0}, "milk", 12)                                    -> milk 12
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free