Design a Vending Machine

Intermediate · 22 min read · Low-Level Design, Case Studies: Core

The State pattern end to end: coins, selection, dispensing and refunds.

The vending machine is the State-pattern problem. Interviewers watch for three things: a clear state diagram, invalid operations handled explicitly in every state, and correct money handling (including change).

What the interviewer expects

The full design in this lesson is longer than anything you'd write in one round. It's there so you understand the edge cases and can answer follow-up questions. In the round itself, aim for this:

1. Requirements

2. States

Writing this table first is the single best thing you can do in the interview — it is the specification of every state class.

3. Class design

4. Implementation

Use integer rupees (or paise) — never double for money.

5. Edge cases to call out

6. Patterns used

7. Extensions

Interview questions

  • Why use the State pattern instead of an enum and switch statements?
  • When is greedy change-making wrong, and how do you fix it?
  • How do you keep an admin restock from interfering with a customer purchase?

Further reading

Key takeaways

  • Start with the state diagram and an operation × state table — it is the spec.
  • Each state class implements valid operations and rejects invalid ones explicitly.
  • Handle money in integers; plan change before committing; refund on any failure.
  • Make change-making a strategy (greedy vs DP) and hardware an interface.

Previous: Design a Parking Lot · Next: Design an Elevator System