LLD · Classic
Vending Machine
Design a vending machine that accepts coins and notes, dispenses products, and returns correct change from limited coin storage.
Simple summary: Customer picks a product, pays, machine checks
stock and payment, dispenses item, then returns change if needed.
Example: Coke costs ₹40; customer inserts ₹50 → machine
dispenses Coke and returns ₹10 change.
1. Clarify requirements
- Fixed product slots with price and quantity.
- Accept coins/notes (or card — usually out of scope).
- Reject payment if product sold out or underpaid.
- Return change using available coin inventory.
- Admin can restock products and refill change.
- Out of scope: remote monitoring, multiple machines networked.
2. Core entities
- Product — id, name, price, quantityInSlot.
- Inventory — map of productId → Product.
- CoinStore — map of denomination → count (for change).
- VendingMachine — state, currentInsertedAmount, select/dispense APIs.
- Transaction — product, paid, changeReturned (audit log).
3. State machine
IDLE → (select product) → AWAITING_PAYMENT
AWAITING_PAYMENT → (insert money) → check total
if total >= price and product available → DISPENSING
if cancel → refund inserted → IDLE
DISPENSING → decrement stock, return change → IDLE
4. Key operations
selectProduct(code):
if inventory[code].qty == 0: return SOLD_OUT
selected = code; state = AWAITING_PAYMENT
insertMoney(amount):
inserted += amount
if inserted >= price(selected):
dispense(selected)
change = inserted - price
returnChange(change)
inserted = 0; state = IDLE
5. Change-making
Use greedy algorithm on standard coin set (works for canonical systems like INR/USD coins). If exact change impossible, fail safely and ask admin — do not dispense product without returning change.
returnChange(amount):
for coin in coins sorted descending:
use = min(amount / coin, coinStore[coin])
dispense use coins; amount -= use * coin
if amount != 0: raise CANNOT_MAKE_CHANGE
6. Concurrency
One customer at a time on a physical machine — lock the whole purchase flow. For software simulation, synchronize inventory and coinStore updates.
7. End-to-end walkthrough
- Customer selects slot B2 (Coke, ₹40, qty 5).
- Inserts ₹20, then ₹20, then ₹10 → total ₹50.
- Machine decrements Coke qty to 4, dispenses product.
- Change ₹10 returned (one ₹10 coin from CoinStore).
Quick revision
- Entities: Product, Inventory, CoinStore, VendingMachine.
- Flow: select → pay → verify → dispense → change.
- Edge cases: sold out, underpaid, cannot make change.
- State machine keeps behaviour clear in interviews.