Build a POS cart with live receipt printing and combo deals
Data Structure DesignModel answerLast updated
Design a point-of-sale cart that prints an itemized receipt on every tap and then extends to apply non-overlapping combo discounts after each update.
You are implementing the core logic for a quick-service restaurant ordering screen. The framework gives you several class stubs and a callback to implement:
MenuItem(id, name, price)— a menu entry with a unique identifier, display name, and unit price.Menu— exposesgetItemById(id)for O(1) lookup.Cart— supportsadd(itemId),remove(itemId), and tracks per-itemquantities.Screen— exposesrender(text)to push a receipt string to the UI.onTapItem(itemId)— invoked by the framework whenever the user taps an item button.
Part A — Live receipt. Every time onTapItem(itemId) fires, add one unit of the item to the Cart, update its quantity, and produce a receipt string that you pass to Screen.render. The receipt must:
- Show one line per distinct item in the format
"name x qty @ unitPrice = lineTotal". - Include a subtotal line and a grand total line at the bottom.
Repeated taps of the same item should aggregate into one line with an increasing quantity. Tapping different items should each produce their own line. Build whatever data structures and formatting helpers you need.
Part B — Combo deals. Now extend the system to support promotional combos. Each Combo is defined by:
k— the minimum number of qualifying items needed to trigger one application,eligibleIds— the set of item IDs that can participate (you may also think of these as categories), and- a discount described by a type (
flatOfffor a fixed currency amount, orpctOfffor a percentage) and a value.
After every item tap, determine some valid collection of non-overlapping combos that apply to the current cart, compute the combined discount, and re-render the receipt so it shows which combos fired and the final discounted total. You do not have to maximize savings or the number of combos — any valid application is acceptable.
In your answer, describe your data model for menu items, the cart, and combos. Provide pseudocode or working code for onTapItem. Explain the algorithm you use to select a valid set of non-overlapping combos (e.g., a single greedy pass with a note on when backtracking would be needed). Analyze time and space complexity. State your assumptions about unique IDs, integer quantities, and rounding rules for percentage discounts.
Hints
Hint 1
Store all monetary values as integer cents to avoid floating-point rounding errors.
Hint 2
Recompute combos from scratch on every tap rather than mutating cart state to remember discounts; this keeps add and remove symmetric and avoids stale-state bugs.
Hint 3
A single greedy pass over combos in priority order, consuming units from a mutable copy of quantities, is enough for a maximal valid set; full backtracking is only needed if the requirement changes to maximizing total discount.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Key idea
Keep money in integer cents throughout so arithmetic is exact. Model the cart as a map itemId -> quantity. Do not store discount state inside the cart. On every tap, recompute everything from the current quantities, apply combos, and render. Recomputing keeps add and remove symmetric and prevents stale-state bugs entirely. The cart is small, so the cost of recomputation is negligible.
Data model
MenuItem(id, name, price)— immutable. Price is in cents.Menu— holds a dictionaryid -> MenuItem;getItemByIdis O(1).Cart.quantities— an insertion-ordered dictionaryid -> qty. Lines appear in the order items were first added.Combo(name, k, eligible_ids, dtype, value):dtypeisFLAT_OFF(value in cents) orPCT_OFF(value as an integer percent).- One application consumes exactly
kunits, all of which must be ineligible_ids.
AppliedCombo(combo, consumed_ids, discount)— records which units were consumed so the receipt can explain each discount line.
Combo selection: greedy single pass
Copy quantities into a mutable pool that tracks remaining units. Iterate over combos in a fixed priority order (the order given). For each combo:
- Expand its eligible item IDs by their remaining counts in
pool, producing a flat list of available units. - Sort those units by price descending (so
PCT_OFFcombos are as generous as possible). Break ties by item ID for determinism. - Split the sorted list into consecutive chunks of size
k. Each full chunk becomes one applied combo instance. - Decrement
poolby one for each unit in every chunk.
This produces a maximal valid set: after we finish a combo, fewer than k of its eligible units remain, and later combos only remove units, so the combo can never become applicable again. One pass is sufficient; no fixed-point iteration is needed.
Why it is correct
- Non-overlapping. A unit is consumed only if it is still in
pool, and consuming it decrements the count. No unit is counted twice. - Valid. Every chunk has exactly
kunits and all belong toeligible_ids. - Maximal. After processing each combo, fewer than
keligible units remain. Later combos only remove units. So no combo can become applicable after its turn passes.
If the requirement changes to "maximize total discount" or "cover every item," you would need a DFS over (combo index, remaining multiset) with memoization on remaining counts. That is a weighted set-packing problem and is NP-hard in general. Mention it, explain why you are not building it, and only implement if the interviewer asks.
Complexity
Let U = total units in the cart, C = number of combos, E = max eligible units for any one combo (E ≤ U).
Per tap:
- Building and sorting each combo's eligible units: O(C · E log E)
- Updating the pool: O(U) overall
- Formatting the receipt: O(d + A) where
dis distinct items andAis applied combos
Total time per tap: O(C · U log U). Space: O(U + d). With realistic carts this runs in microseconds.
Assumptions and edge cases
- Item IDs are unique. An unknown ID raises an error; the cart is not modified.
- Quantities are positive integers. Removing at quantity 1 deletes the line. Removing a missing item is a no-op.
FLAT_OFFis capped at the sum of consumed unit prices so no line goes negative and the total stays ≥ 0.PCT_OFFis applied to the sum of thekconsumed units, rounded half-up to the cent:(total * pct + 50) // 100.- Combo priority is the list order provided. Output is deterministic because ties break by item ID.
- Categories can be expanded into
eligible_idsat construction time. - An empty cart prints subtotal 0.00 and total 0.00.
Python solution
from dataclasses import dataclass
from enum import Enum
def fmt(cents: int) -> str:
sign = "-" if cents < 0 else ""
c = abs(cents)
return f"{sign}{c // 100}.{c % 100:02d}"
@dataclass(frozen=True)
class MenuItem:
id: str
name: str
price: int # cents
class Menu:
def __init__(self, items):
self._items = {item.id: item for item in items}
def getItemById(self, item_id: str) -> MenuItem:
if item_id not in self._items:
raise KeyError(f"unknown item: {item_id}")
return self._items[item_id]
class Cart:
def __init__(self):
self.quantities: dict[str, int] = {} # insertion-ordered
def add(self, item_id: str, qty: int = 1):
self.quantities[item_id] = self.quantities.get(item_id, 0) + qty
def remove(self, item_id: str, qty: int = 1):
if item_id not in self.quantities:
return
self.quantities[item_id] -= qty
if self.quantities[item_id] <= 0:
del self.quantities[item_id]
class DiscountType(Enum):
FLAT_OFF = "flatOff"
PCT_OFF = "pctOff"
@dataclass(frozen=True)
class Combo:
name: str
k: int
eligible: frozenset
dtype: DiscountType
value: int # cents for FLAT_OFF, whole percent for PCT_OFF
def discount_for(self, unit_prices: list[int]) -> int:
base = sum(unit_prices)
if self.dtype is DiscountType.FLAT_OFF:
return min(self.value, base)
return (base * self.value + 50) // 100 # round half-up
@dataclass(frozen=True)
class AppliedCombo:
combo: Combo
item_ids: tuple
discount: int
def find_combos(cart: Cart, menu: Menu, combos: list[Combo]) -> list[AppliedCombo]:
pool = dict(cart.quantities)
applied = []
for combo in combos:
# expand eligible units still in the pool
units = [
iid
for iid in sorted(combo.eligible)
for _ in range(pool.get(iid, 0))
]
# highest price first; tie-break by id for determinism
units.sort(key=lambda iid: (-menu.getItemById(iid).price, iid))
for start in range(0, len(units) - combo.k + 1, combo.k):
chunk = units[start:start + combo.k]
for iid in chunk:
pool[iid] -= 1
prices = [menu.getItemById(iid).price for iid in chunk]
applied.append(AppliedCombo(combo, tuple(chunk), combo.discount_for(prices)))
return applied
def build_receipt(cart: Cart, menu: Menu, applied: list[AppliedCombo]) -> str:
lines = []
subtotal = 0
for iid, qty in cart.quantities.items():
item = menu.getItemById(iid)
line_total = item.price * qty
subtotal += line_total
lines.append(f"{item.name} x {qty} @ {fmt(item.price)} = {fmt(line_total)}")
discount = sum(a.discount for a in applied)
total = subtotal - discount
out = list(lines)
if applied:
out.append("--- Promos ---")
for a in applied:
names = [menu.getItemById(i).name for i in a.item_ids]
out.append(f"{a.combo.name} ({', '.join(names)}) -{fmt(a.discount)}")
out.append(f"Subtotal: {fmt(subtotal)}")
if applied:
out.append(f"Discounts: -{fmt(discount)}")
out.append(f"Total: {fmt(total)}")
return "\n".join(out)
class POS:
def __init__(self, menu: Menu, combos: list[Combo], screen):
self.menu = menu
self.combos = combos
self.screen = screen
self.cart = Cart()
def onTapItem(self, item_id: str):
item = self.menu.getItemById(item_id) # raises if unknown
self.cart.add(item_id)
applied = find_combos(self.cart, self.menu, self.combos)
receipt = build_receipt(self.cart, self.menu, applied)
self.screen.render(receipt)
The POS class wires everything together: each tap adds to the cart, recomputes combos from scratch, builds the receipt string, and pushes it to the screen. The design is deliberately stateless across taps except for the cart's quantity map, which keeps the logic easy to reason about and test.