← Questions
Design a vending machine
0
I was asked this
No reports yet. Sign in to say where you were asked it.
An object-oriented design interview question asked at Amazon. It tests object-oriented design.
Design a vending machine in code. It holds products in slots, accepts coins and notes, lets the customer select a product, takes payment, gives change and handles sold-out items. Model it with clear states so each action is only accepted when it makes sense.
Requirements
- Functional: show products with slot codes and prices; accept coins and notes and keep a running balance; select a product: if it is sold out, say so; if the balance is short, ask for more; otherwise dispense the product and return change; cancel at any time to get the inserted money back; an operator restocks products and refills the change float.
- Give change from the coins the machine actually holds, and refuse a sale (refunding the money) if exact change cannot be made.
- Non-functional: money in integer cents; one customer at a time; adding a payment method (cards) does not rewrite the machine.
Clarifying questions
- Which coins and notes are accepted?
- Can the customer select first and pay after, or must they pay first?
- What if the product jams and does not drop?
- Can a customer buy several items with one balance?
- Is card payment in scope now or later?
What a strong answer covers
- Core classes:
VendingMachine(the façade),Slot(code, product, count, price),Product,Inventory,CoinBoxorCashRegister(denominations held,make_change(amount)),MoneyorDenomination, and aStateinterface withIdle,HasMoney,DispensingandOutOfService. - The state pattern: each state accepts or rejects
insert,select,cancelanddispense, so invalid sequences are handled in one place. - Change making from limited coins: greedy works for standard coin systems when supply is unlimited, but with limited coins you need a check (or a small search) and must refuse the sale if change is impossible.
- Committing a sale only after dispensing and change both succeed, and refunding otherwise.
- Tests: exact payment, change needed, no change possible, sold out, cancel with money in.
Follow-ups
- Add card and mobile payments.
- The machine reports stock and sales to a server for restocking routes.
- Add promotions, such as a discount on a second item.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Draw your answer hereBoxes, arrows and notes, saved for you to come back to.Sign in to start drawing
