Skip to the content

Stock at closing time

Problem

Beto pulls down the shutter of his auto parts shop and wants to write down what is left on the shelf, so he knows what to order tomorrow. New parts came in during the day, the ones he sold went out, and all of that is in his notebook.

Write a function that takes shelf, a dictionary with what he had when he opened (the part is the key and how many there are is the value; it may come empty), and moves, a list where each move is ["part", amount]: a positive amount means parts came in and a negative one means they went out. Return a new dictionary with what is left at closing time, without touching the one you got: Beto keeps the morning one to compare.

A part that was not on the shelf is added as soon as it arrives, and whatever ends at zero does not show up, whether a move took it there or that is how the shelf already was. He never sells more than he has, so no amount ends up negative.

With {"pad": 4, "plug": 10} and the moves [["plug", -10], ["filter", 3], ["pad", 2]] you return {"pad": 6, "filter": 3}: the pads went up to 6, the filter is a new part and the plugs ran out.

If the shelf was empty and nothing moved, you return an empty dictionary.

Examples

  • The example

    {"pad": 4, "plug": 10}, [["plug", -10], ["filter", 3], ["pad", 2]] → {"pad": 6, "filter": 3}

  • Nothing moved

    {"oil": 2, "bulb": 6}, [] → {"oil": 2, "bulb": 6}

  • A part that was not there

    {"pad": 1}, [["nail", 5]] → {"pad": 1, "nail": 5}

  • The only part in stock ran out

    {"bulb": 3}, [["bulb", -3]] → {}

  • The same part comes in and goes out

    {"belt": 2}, [["belt", 5], ["belt", -4]] → {"belt": 3}

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def closing_stock(shelf, moves):
    pass

JavaScript

function closingStock(shelf, moves) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →