Build a Grouped, Promo-Aware, Sorted Receipt Printer
Data Structure DesignModel answerLast updated
Extend a cart class that turns scanned item names into a receipt: itemized total, grouping by type, a buy-three-get-two-free deal, then alphabetical ordering.
You are given a small ShoppingCart class that stores scanned items in a plain list. It has addItem and removeItem methods, and some existing code prints a receipt from it. Items arrive as a stream of name strings. Your job is to evolve the cart through four requirements, each building on the last. Most of the design effort belongs in the cart and its collaborators, not in the printing code.
Use these prices for the examples:
cheese 4.00 bread 2.50 apple 0.75
Stream: "cheese", "bread", "cheese", "apple", "cheese"
Requirement 1: itemized receipt. Print one line per scanned item, in scan order, with its price. End with a total line.
cheese 4.00
bread 2.50
cheese 4.00
apple 0.75
cheese 4.00
Total 15.25
Requirement 2: grouped receipt. Print one line per item type in the form name, quantity, unitPrice xquantity. Adding and removing items must still work, including removing the last unit of a type.
cheese, 3, 4.00 x3
bread, 1, 2.50 x1
apple, 1, 0.75 x1
Total 15.25
Requirement 3: promotion. Add a "buy three, get two free" deal for one specific item. The receipt line for that item must reflect the deal. All other items are unaffected.
Requirement 4: sorted receipt. Print the item lines in alphabetical order of name.
apple, 1, 0.75 x1
bread, 1, 2.50 x1
cheese, 3, 4.00 x3
Total 15.25
Before coding, state your assumptions: where prices come from, how money is stored and formatted, what happens on removing an absent item, how names are normalized (case, whitespace), and exactly what the promotion means for partial groups. Then explain your design and implement it, with attention to the cost of each cart operation and to how you would test it.
Hints
Hint 1
Store money as integer cents and format only at print time, so totals never suffer floating-point drift.
Hint 2
Replace the list with a map from item name to count. Add and remove become O(1), and removing the last unit of a type should delete the key so it never prints a zero-quantity line.
Hint 3
Model the promotion as a separate object that answers 'how many units are payable for this quantity?'. The cart and printer then only ask for payable units and never special-case an item.
Hint 4
Sort at print time (O(k log k) for k distinct types) rather than on every add, and normalize names to a single case so ordering and grouping agree.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to state first
- Each stream entry is just an item name. Prices come from a catalog (name to price), not from the stream.
- Names are trimmed and lowercased, so
" Cheese"and"cheese"are the same type. Blank or unknown names are rejected, not silently added. - Money is stored as integer cents and formatted as
D.CConly when printing. - Removing an item that is not in the cart is a no-op that returns
False, so the caller can decide how to react. - Promotion meaning: in every complete group of five scanned units of the promoted item, three are paid and two are free. A partial group earns nothing, so four units pay for four. (If the interviewer means "every three bought adds two free units", only the payable-units function changes.)
Design
Three responsibilities, kept apart:
- Cart storage holds counts per item type.
- Pricing and promotions decide how many units are payable for a given quantity.
- Receipt formatting turns lines and a total into text.
Why change the storage
A list makes removeItem O(n) (find, then shift), and grouping needs an O(n) pass at print time. A hash map from name to count gives O(1) add and remove, and printing is O(k) over distinct types. Python dicts and Java's LinkedHashMap also keep insertion order, which is what requirement 2 shows when order is unspecified.
If requirement 1's scan-order output must keep working, keep an append-only scan log next to the map. Removing from the log costs O(n), so I would mention it and ask whether the old format is still needed. Usually it is not.
The promotion as an abstraction
A promotion answers one question: given quantity q, how many units are charged? The cart holds a map from item name to promotion. This keeps the deal out of add, remove and the printer, and allows other deals later (for example "buy two, get one free") without touching existing code.
For buy-3-get-2 with a group size of 5: full, rest = divmod(q, 5), and the payable count is full * 3 + rest.
| Scanned | Payable (partial groups pay full) |
|---|---|
| 3 | 3 |
| 4 | 4 |
| 5 | 3 |
| 7 | 5 |
| 10 | 6 |
A removal needs no special promotion logic. Because payable units are derived from the current count on each print, removing a unit from 5 gives 4 scanned and 4 payable, and the discount disappears automatically. Never store a precomputed discount, since it would go stale.
Code (Python)
from dataclasses import dataclass
class NoPromotion:
def payable(self, qty: int) -> int:
return qty
@dataclass(frozen=True)
class BuyNGetMFree:
n: int = 3
m: int = 2
def payable(self, qty: int) -> int:
full, rest = divmod(qty, self.n + self.m)
return full * self.n + rest
def money(cents: int) -> str:
return f"{cents // 100}.{cents % 100:02d}"
class Cart:
def __init__(self, prices_cents: dict, promotions: dict | None = None):
self._prices = {k.lower(): v for k, v in prices_cents.items()}
self._promos = {k.lower(): v for k, v in (promotions or {}).items()}
self._counts: dict[str, int] = {}
@staticmethod
def _norm(raw: str) -> str:
return raw.strip().lower()
def add(self, raw: str) -> bool:
name = self._norm(raw)
if not name or name not in self._prices:
return False
self._counts[name] = self._counts.get(name, 0) + 1
return True
def remove(self, raw: str) -> bool:
name = self._norm(raw)
n = self._counts.get(name, 0)
if n == 0:
return False
if n == 1:
del self._counts[name] # no zero-quantity lines
else:
self._counts[name] = n - 1
return True
def receipt(self) -> str:
lines, total = [], 0
for name in sorted(self._counts): # requirement 4
qty = self._counts[name]
unit = self._prices[name]
promo = self._promos.get(name, NoPromotion())
pay = promo.payable(qty)
total += unit * pay
lines.append(f"{name}, {qty}, {money(unit)} x{pay}")
lines.append(f"Total {money(total)}")
return "\n".join(lines)
Usage:
cart = Cart({"cheese": 400, "bread": 250, "apple": 75},
{"cheese": BuyNGetMFree()})
for s in ["cheese", "bread", "cheese", "apple", "cheese"]:
cart.add(s)
print(cart.receipt())
# apple, 1, 0.75 x1
# bread, 1, 2.50 x1
# cheese, 3, 4.00 x3
# Total 15.25
Adding two more cheeses makes five scanned, so the line reads cheese, 5, 4.00 x3 and the total is 0.75 + 2.50 + 12.00 = 15.25.
Complexity
| Operation | List version | Map version |
|---|---|---|
| add | O(1) | O(1) |
| remove | O(n) | O(1) |
| receipt | O(n) | O(k log k) from sorting, k distinct types |
If receipts were printed far more often than items change, a sorted map (TreeMap, or a sorted container) would make printing O(k) at the cost of O(log k) updates. For a retail cart, k is tiny, so sorting at print time is the simpler choice.
Testing
- The sample stream gives total 15.25 and the expected grouped lines.
- Removing the only unit of a type deletes its line and lowers the total.
- Removing an absent item returns
Falseand changes nothing. - Promotion boundaries: quantities 4, 5, 6 and 10 of the promoted item, plus removing from 5 back to 4.
- Blank, unknown and mixed-case names.
Common mistakes
- Using floats for money, which produces totals like
15.249999. - Leaving a zero-quantity entry after the last removal.
- Hard-coding the promoted item's name inside
addor the printer. - Storing a discount at add time, so removals leave a wrong total.
- Sorting case-sensitively so
Breadlands beforeapple, or sorting on every add instead of once at print time. - Coding before settling the promotion semantics for partial groups.