Start learning free

LESSON 132 OF 291 · DICTIONARIES - CHALLENGES

Restock in Kotlin: Updating a MutableMap Value

Practice Read the full explanation

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

    KOTLIN · DICTIONARIES - CHALLENGES

    Restock in Kotlin, explained

    Problem overview

    The function restock receives inventory, a map from item names to counts, an item and an amount. A delivery brings amount more of item. The function adds the amount to that item's count and returns the map. Other entries stay as they are, and the order of the entries doesn't matter.

    With {"apples": 5, "bananas": 2, "cherries": 10}, item = "bananas" and amount = 3, the result is {apples=5, bananas=5, cherries=10}. With {"milk": 0} and 12, the result is {milk=12}. The item is always a key already, and the amount is at least 1.

    Approach

    Read the old count, add the amount, and store the sum under the same key. The first instinct is inventory[item] += amount, but it doesn't compile. Reading inventory[item] gives an Int?, because the key might be missing, and the compiler reports:

    error: operator call is prohibited on a nullable receiver of type 'Int?'. Use '?.'-qualified call instead.
    

    The lesson guarantees the key exists, so !! turns the Int? into an Int and the addition works.

    Step by step

    1. Write the new count. Assign to inventory[item], which stores a value under that key. The value is the old count, inventory[item]!!, plus amount.
    2. Return inventory. The map was changed in place, so it already holds the updated count and every other entry.

    The solution in Kotlin

    class Solution {
        fun restock(inventory: MutableMap<String, Int>, item: String, amount: Int): MutableMap<String, Int> {
            inventory[item] = inventory[item]!! + amount
            return inventory
        }
    }
    

    Some details worth knowing:

    • Assignment replaces the value. inventory[item] = value calls set, which overwrites the old count when the key exists and adds a new entry when it doesn't.
    • !! throws on null. If the key were missing, inventory[item]!! would throw a NullPointerException. The lesson rules that case out.
    • MutableMap is required. A read-only Map has no set, so the assignment wouldn't compile on one.
    • Map output looks like {k=v}. Printing a Kotlin map shows {apples=5, bananas=5, cherries=10}, with = between key and value.

    When the key might be missing

    This lesson promises that item is already in the map, which is why !! is enough. If it might be new, give the missing case a starting count with the Elvis operator, ?:, which uses its right side when the left side is null:

    val inv = mutableMapOf("pens" to 7)
    inv["ink"] = (inv["ink"] ?: 0) + 4
    println(inv) // {pens=7, ink=4}
    

    Here "ink" isn't in the map, so the count starts at 0 and the assignment adds a new entry. The same line also works for keys that are present.

    Complexity

    Time is O(1) on average: one read and one write in a hash map, whatever the number of items. Space is O(1) extra, since the map is updated in place rather than copied.

    Why returning the same map is fine

    The function changes the map it was given and hands the same map back. That is a normal pattern for a mutable collection: the caller's variable and the returned value refer to one map, so both see the new count. If you needed the original untouched, you would copy it first with toMutableMap(), but this lesson asks for the in-place update.

    Edge cases and common mistakes

    • A count of 0. It is still a value in the map, so the key is present and the addition gives 0 + amount.
    • Assigning the amount. inventory[item] = amount would drop the old count instead of adding to it.
    • Changing other entries. Only the key item is written, so the other counts keep their values.

    Testing

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