Problem framing
A vending machine accepts coins, lets users select items, dispenses product, returns change. Tests state machine modeling, inventory, and whether you reach for State pattern vs spaghetti if/else.
| State | Allowed actions | Transitions |
|---|---|---|
Idle | insertCoin | coin → HasMoney |
HasMoney | insertCoin, selectItem, returnCoins | select → Dispensing; return → Idle |
Dispensing | (internal) dispense + change | done → Idle or SoldOut |
SoldOut | returnCoins only | restock → Idle |
Core classes
VendingMachine holds current State, Inventory, CoinStore. Each state implements VendingState with insertCoin(), selectItem(), dispense(). Inventory maps slotId → Product with quantity. CoinStore tracks inserted value and available change denominations.
Why State over enums + switch
With 4 states, a switch works — but say: "State pattern localizes transition logic; adding MaintenanceMode is one new class, not editing every branch." Map transitions on the whiteboard before writing classes.
Change-making subproblem
Greedy works for canonical coin systems (US quarters); arbitrary denominations may need DP — mention only if asked. For LLD, CoinStore tracks counts per denomination and makeChange(amount) returns coins or fails.
Senior-level signal
Walk through insufficient change: machine rejects selection or refunds — state where invariants matter. Mention that selectItem() should validate inventory and sufficient credit atomically. Defer: multi-item selection, card payment, admin restock API.
Where this goes next
Library Management System introduces catalog vs inventory separation and reservation workflows — a richer entity model with M:N relationships.
Further Reading
Practice Tasks (Optional)
Design or implement locally in any language — no autograding. Focus on class structure, extensibility, and being able to explain trade-offs out loud.
- Draw state diagram and class mapping30m
Draw states and transitions for a vending machine. Map each state to a class implementing a common interface. Implement selectItem() and insertCoin() transitions on paper.