2dbi

Design a vending machine

viaLeetCode

Problem Object-oriented design of a vending machine: products and inventory, money handling (coins/cash), selection, dispensing, and change — driven by explicit state transitions.

Requirements

  • insertMoney(denomination), selectProduct(code), dispense, refund/cancel; reject selection when unpaid or out of stock; return correct change or fail gracefully when change can't be made; admin restock/collect.

Core design

  • STATE pattern is the expected centerpiece: states Idle → HasMoney → Dispensing (+ OutOfService); each state class implements the operations legally (insertMoney in Idle → HasMoney; selectProduct in HasMoney validates stock & funds), illegal ops rejected uniformly. VendingMachine holds current State and delegates.
  • Supporting classes: Product, Inventory(slot code → product, count), CashRegister/ChangeMaker (denomination counts; change via greedy for canonical coin systems — note greedy fails for arbitrary sets, DP fallback), Transaction capturing inserted amount.

Discussion points

  • Why state over if/else flags: transitions become explicit and new states (maintenance, card payment) don't ripple through every method.
  • Change-making edge cases: insufficient change → refuse sale upfront vs refund; exact-change-only mode.
  • Extensibility probes: card/UPI payments (PaymentStrategy), multi-item carts, telemetry/restock alerts (observer); concurrency if networked (per-machine serialization).
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account