AlgoViz

Design a vending machine

medium 90 min

Build a vending machine around its money: coins in escrow, change from a limited box, stock by place, a slow motor that can jam, and several events that arrive at once.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

Theory

Read or listen first. About 2 min.

What it is

A vending machine is a shop without a person. It takes money, checks, gives a product, gives change, and must be right when nobody is there to say sorry.

Underneath it is a small transaction over two things that cannot be rolled back easily: coins that have fallen and cans that have fallen. The trick is to do everything that can fail before either of them moves.

It is also the standard example for state machines. That half is on the State pattern page. This page owns money, change, stock and races.

Why it exists

The domain is known to everyone, so the interview reaches design within a minute.

It hides a real algorithm (change from a limited stock), a real protocol (hold, act, take) and a real race (the three seconds of the motor) behind a toy.

Every checkout, cash machine and ticket counter has the same order of steps. Whoever understands the hatch understands them.

A short history

  1. 1st century

    Hero of Alexandria describes a machine that gives holy water or wine for a coin: the coin falls on a pan, a lever opens a valve.

  2. 1883

    Percival Everitt invents a machine that sells postcards. Such machines soon stand in railway stations and post offices in London.

  3. 1895

    The first automat, Quisisana, opens in Berlin: a restaurant with coin operated hatches.

  4. 1902

    On 12 June Horn and Hardart open the first automat in the United States, in Philadelphia.

  5. 1994

    The book Design Patterns describes State, the pattern most people name first for this machine.

Words to know

Escrow
Coins inserted but not taken yet. They belong to the customer.
Coin box
The machine's own coins, counted by kind.
Float
Coins left in the box on purpose, for change.
Change making
Finding coins that add up to an amount.
Greedy
Always the largest coin that fits. Fast, not always possible.
Claim
Look and take one piece in one step.
Settle
Move coins between owners after the product is out.
Authorise and capture
Reserve money on a card, take it later.
Idempotent
Doing it twice has the result of doing it once.
Journal
A record written before the act, used after a crash.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Coins in. Each coin lies in escrow and still belongs to the customer

Understand it

Start here

The deckchair hatch

At the seaside, Asha rents deckchairs from a wooden hatch. A chair costs 70 cents. There is a tray for the customer's coins and a box with Asha's own. Watch when a coin moves from the tray to the box: that moment is the whole problem.

A morning at the deckchair hatch
CHAIR 70TRAYBOX25x 110x 4100x 0

Tray before box. Ask for change before the chair. Then every refusal is cheap.

What an interviewer looks for here

  • Money as coins

    Whole cents, and a count of each coin. A sum cannot be paid out.

  • Whose is it?

    Escrow is the customer's, the box is the owner's. One method moves coins between them.

  • The order of steps

    Check, plan change, claim, drop, settle. Each refusal costs nothing.

  • The slow motor

    Three seconds in which a second press, a coin or a cancel may arrive.

Questions

Six questions, and what each answer changes

AskIf the answer isThen
Coins only, or notes and cards?Coins and notesNotes are values of the same enum that the box cannot pay out
Must it give change?YesThe box is counted by coin, and the search uses the stock
What if it cannot?RefuseNoChange before the motor runs. A lamp says exact money only
Choose first or pay first?Eitherbuy looks at what is inserted when it is called
Can the product fail to fall?YesThe motor may report a jam. The claim is put back
Who else touches it?A technician, an appA lock, a busy flag, and later reservations

One purchase

The plan is made before the claim, the claim before the drop, and the coins move last.

Design, first try

The design most people draw first

The design to avoid: beautiful states around a bare number

VendingMachine- balance: int- selected: Product- inventory: Map+ insertMoney(amount: int)+ selectProduct(code)+ setState(state)+ setBalance(int)

1/4Money is a number

insertMoney(100) adds 100 to a balance. Which coins came in is forgotten. So nobody can say whether 30 cents can be given back.

usesimplementshas (lives on)owns (dies together)

The states are right and the money is wrong: change is printed and never counted out.
Python
class Machine:    def __init__(self):        self.balance, self.quantity, self.price = 0, 1, 70    def insert(self, cents):        self.balance += cents    def select(self):        if self.balance < self.price:            return "more money"        self.quantity -= 1                       # it has not even fallen yet        change = self.balance - self.price        self.balance = 0        return f"here is your juice and {change} cents"   # from where?m = Machine()m.insert(100)print(m.select())m.insert(100)print(m.select(), "| left:", m.quantity)
It promises 30 cents without owning a single coin, and sells a juice it does not have: left: -1.
Edit and run it in your browser

Design, better

The design to reach

The design to reach: whose coins are these?

VendingMachine- escrow: List<Coin>- busy: bool- lock: Lock+ insert(coin): int+ cancel(): List<Coin>+ buy(code): Sale«enum»Coin5, 10, 25, 100

1/5Coins, not a number

The customer's coins lie in escrow, as a list. They are not ours until something falls. cancel gives back the very same coins.

owns (dies together)useshas (lives on)depends on

Display and keypad are missing on purpose: they call and show, and remember nothing.

What each class owns

ClassKnowsDoesDoes not know
VendingMachineEscrow, busy, the order of stepsinsert, cancel, buyHow change is found
CoinBoxHow many of each coinPlans and settlesPrices, products
make_changeNothingFewest coins from a stockWhose coins they are
InventoryProducts, counts, broken placesClaims one, puts it backMoney
MotorThe hardwareDrops, or reports a jamEverything else

Change

Why greedy is not enough

For many real coin systems, the greedy rule (largest coin first) gives the fewest coins if you have enough of each. A machine has not. Take 30 cents, one quarter and four dimes: greedy takes the quarter, needs 5, and gives up. Three dimes were there.

AmountStockGreedyBest
3025 x 1, 10 x 425, then stuck10 + 10 + 10
4025 x 1, 10 x 4, 5 x 125 + 10 + 5The same
3025 x 1, 10 x 125, then stuckImpossible: refuse
6coins 1, 3, 4 without limit4 + 1 + 13 + 3
0AnythingNothingNothing: a plan with no coins
The last but one row shows the other kind of failure: a system of coins for which greedy is never safe, even with plenty.

Building sums, coin by coin: stock 25 x 1 and 10 x 4, amount 30

Work

O(A5⋅∑cmin⁡(nc,A/c))O\left(A_5 \cdot \sum_c \min(n_c, A / c)\right)
A is the amount, A5 is the number of sums up to A (A / 5 with coins of 5 and more), n the stock of coin c. For 95 cents: at most 20 sums times 31 coins, about 600 small steps.

How do you find the change?

BreaksPrint the difference
How
change = balance - price
Limit
A number is not a coin. The machine may not have it.
Choose when
Never.
WorksGreedy over the stock
How
Largest first, at most what is there.
Limit
Refuses sales it could make, as with 25 and four 10s.
Choose when
If you say so, and the box is always well filled.
StrongSearch with the stock
How
Dynamic programming: for each sum, the shortest list of coins.
Limit
Ten more lines. Needs an upper bound for the amount.
Choose when
Here. Amounts are small.

States

The moods, derived

The same four moods, without a state field

Idle: escrow is empty. HasMoney: it is not. Dispensing: busy. SoldOut is not a mood of the machine but a count of zero at one place.

What each action does in each mood

ActionIdleHasMoneyDispensing
insertCoin into escrowCoin into escrowBusy: coin falls through
buyNotEnough(price)Sale, or a refusalBusy
cancelEmpty listAll coins backBusy
Nine cells, three ifs. The State pattern page shows the version with a class for each column and says when it pays: many moods, different answers.

The hard part

Three seconds

The motor turns for about three seconds. In this time a child presses the button again, somebody throws another coin, and the customer presses cancel. All three look at the same escrow.

Press twice without a busy flag

The escrow is emptied after the drop, so both presses see it full. Emptying it first is no cure: after a jam the coins would be gone.

How do you protect the three seconds?

BreaksHold the lock while the motor turns
How
One big with lock around buy.
Limit
Every other thread waits for three seconds: no refusal, no display, no technician. And the second press is queued, then sells again if there is money.
Choose when
Never around hardware.
WorksEmpty the escrow first
How
Take the coins, drop, give back on a jam.
Limit
A crash in between eats the money in silence.
Choose when
With a journal.
StrongA busy flag under a short lock
How
Lock: check and claim, set busy. Unlock: drop. Lock: settle.
Limit
Two short critical sections, and the flag must be cleared on every known result.
Choose when
Here.

Summary

The whole topic in one minute.

Coins are a list in escrow until something has fallen. Change is planned from the box and the escrow with a search, before the product. The order is check, plan, claim, drop, settle, and each refusal moves nothing.

A short lock covers the decisions, a busy flag covers the motor. A known jam puts everything back, an unknown result stops the machine. Cards fit the same shape: hold, take, release.

  • Whole cents, and coins by kind: a sum cannot be paid out.
  • Escrow belongs to the customer until something has fallen.
  • Plan the change before the product, with the stock you have.
  • Order: check, plan, claim, drop, settle.
  • No lock while the motor turns: a busy flag says no at once.
  • An unknown result stops the machine. A known jam gives everything back.

Sources