Cart Pricing Engine: Offers, Cheapest Deal, Aisle Sort
Arrays & HashingModel answerLast updated
Parse cart records, total units and price in integer cents, apply the best percent-off or buy-N-get-M-free deal per product, then sort items by aisle with frozen goods at the end.
You are building the checkout logic for an online grocery cart. The cart arrives as text, one product per line. Build it in three stages, and agree on the input format and rules before you start coding.
For concreteness, assume this format (you may propose another, but state it):
name,unit_price,quantity,aisle,frozen
milk,3.49,2,4,no
pizza,6.00,3,9,yes
apples,0.50,6,,no
Offers are given separately:
milk: 10% off
pizza: buy 2 get 1 free
pizza: 25% off
Stage 1: Totals
Parse every record and report:
- the total number of units in the cart
- the total price
Decide how to handle malformed lines (wrong field count, non-numeric or negative values, bad quantity), a product that appears on several lines, and a missing aisle. Use an exact money representation.
Stage 2: Offers
Support two offer types:
- Percentage off: a product's price is reduced by a given percent.
- Buy N, get M free: for every group of N paid units, M further units are free.
A product may have several offers. Only the one that gives that product the lowest price applies; offers are never combined. Report the total discount in addition to the final price. Think about quantities that do not fill a whole group (for example 5 units under "buy 2 get 1 free") and where percentage results are rounded.
Adding a third offer type later should not require changes to the totals code.
Stage 3: Ordering
Return the cart items sorted by aisle, with all frozen items after every non-frozen item. Define what happens with ties and with items that have no aisle.
Expected
Working code (or detailed pseudocode), the rules you chose and why, and the complexity of each stage.
Hints
Hint 1
Store money as integer cents and parse the price text with a decimal type, not a float. Round only once, at a clearly defined point (for example per product line), with an explicit rule such as half-up.
Hint 2
For buy N get M free, a full group is N+M units and costs N units. Leftover units cost min(leftover, N) units. Compute every candidate cost for a product, including full price, and take the minimum.
Hint 3
Model each offer as an object with a method that returns the cost of a line, so totals only call that method. For ordering, a single sort with a tuple key such as (is_frozen, aisle_missing, aisle, name) does everything, and sort stability gives deterministic ties.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Decisions to settle first
State these assumptions out loud before coding:
- Money is stored as integer cents. Prices are parsed with
Decimal, and a price with more than two decimal places is rejected. - Units in the total count every unit in the cart, including units that are free under an offer. The price is what the customer pays.
- Rounding happens once per product line, using half-up on the discounted line total.
- Repeated products: lines with the same name are merged by summing quantity. If their unit prices disagree, that is a data error and is reported.
- Malformed lines are collected as errors with their line number and skipped, so one bad row does not abort the whole cart.
- Offers never stack. For each product the cheapest result among "no offer" and every matching offer is used.
Stage 1: Parsing and totals
Split each line on commas and trim fields. Require five fields. Validate that the price is a non-negative decimal with at most two places, the quantity is a positive integer, the aisle is empty or an integer, and the frozen flag is yes or no. Return an Item dataclass or raise ValueError with a reason. Merge into a dict keyed by name. Total units is the sum of quantities, and the base total is the sum of qty * unit_cents. This is O(n).
Stage 2: Offers
The two cost formulas for a line with q units at u cents:
- Percent p:
(q*u*(100-p) + 50) // 100, integer half-up rounding with no floats. - Buy N get M free:
group = N + M,full, rest = divmod(q, group), paid units= full*N + min(rest, N), cost= paid*u.
Example: 5 units of a 6.00 item under buy 2 get 1 free gives one full group (2 paid) plus 2 leftover (2 paid), so 4 paid units, 24.00. Compare with 25% off: 30.00 * 0.75 = 22.50, which is cheaper, so 25% off wins for that product.
For extensibility, each offer implements one method, cost(item) -> int. The pricing code never inspects offer types, so a new type (for example "2 for a fixed price") is just another class.
Stage 3: Ordering
One sort with a composite key:
key = (item.frozen, item.aisle is None, item.aisle or 0, item.name)
False < True, so non-frozen items come first and frozen items last. Within each group, items with an aisle come before items without, then ascending aisle, then name for deterministic ties. Python's sort is stable, so equal keys keep input order. Cost is O(n log n).
Code
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import Protocol
@dataclass
class Item:
name: str
unit: int # cents
qty: int
aisle: int | None
frozen: bool
def to_cents(text: str) -> int:
try:
d = Decimal(text) * 100
except InvalidOperation:
raise ValueError(f"bad price {text!r}")
if d < 0 or d != d.to_integral_value():
raise ValueError(f"bad price {text!r}")
return int(d)
def parse_line(line: str) -> Item:
f = [x.strip() for x in line.split(",")]
if len(f) != 5 or not f[0]:
raise ValueError("expected 5 fields")
if not f[2].isdigit() or int(f[2]) == 0:
raise ValueError("bad quantity")
if f[3] and not f[3].isdigit():
raise ValueError("bad aisle")
if f[4] not in ("yes", "no"):
raise ValueError("bad frozen flag")
return Item(f[0], to_cents(f[1]), int(f[2]),
int(f[3]) if f[3] else None, f[4] == "yes")
def load(lines):
items, errors = {}, []
for no, line in enumerate(lines, 1):
try:
it = parse_line(line)
except ValueError as e:
errors.append((no, str(e)))
continue
old = items.get(it.name)
if old is None:
items[it.name] = it
elif old.unit != it.unit:
errors.append((no, "conflicting price"))
else:
old.qty += it.qty
return list(items.values()), errors
class Offer(Protocol):
def cost(self, item: Item) -> int: ...
@dataclass
class PercentOff:
pct: int
def cost(self, item):
return (item.qty * item.unit * (100 - self.pct) + 50) // 100
@dataclass
class BuyGetFree:
n: int
m: int
def cost(self, item):
full, rest = divmod(item.qty, self.n + self.m)
return (full * self.n + min(rest, self.n)) * item.unit
def summarize(items, offers): # offers: dict[name, list[Offer]]
units = base = total = 0
for it in items:
line = it.qty * it.unit
best = min([line] + [o.cost(it) for o in offers.get(it.name, [])])
units += it.qty
base += line
total += best
return units, total, base - total # units, price, discount
def shelf_order(items):
return sorted(items, key=lambda i: (i.frozen, i.aisle is None,
i.aisle or 0, i.name))
Complexity
Parsing and pricing are O(n + total offers). Sorting is O(n log n). Memory is O(n).
Trade-offs and common mistakes
- Using floats for money produces off-by-a-cent errors. Use integers or
Decimal. - Rounding per unit versus per line gives different totals. Pick one, document it, and test it.
- Treating leftover units wrongly in buy-N-get-M: leftovers must not receive a free unit unless they complete a group of N paid units, which
min(rest, N)handles. - Stacking offers instead of choosing the cheapest one.
- Hard-coding offer types with
if/elifinside the totals loop, which blocks extension. - Sorting frozen items separately and concatenating works, but a single composite key is simpler and less error-prone.
- Failing the whole cart on one bad line, with no error report.
Tests worth writing
Empty cart, a single item, quantity 1 under buy 2 get 1 free, quantity exactly a multiple of the group size, quantity with a remainder, a percentage that needs rounding (for example 3.49 at 10% off), two offers where each wins for a different quantity, missing aisle, all items frozen, and malformed lines mixed with valid ones.