Grocery Cart Totals, Best-Offer Promotions, and Store Picking Order
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a three-stage checkout and fulfillment module for an online grocery store. Given raw text lines describing cart entries and active product offers, your code must validate and merge records using exact cent arithmetic, apply the single best promotion for each product, and sort valid products into an in-store picking sequence.
Data Types
Use the following NamedTuple and alias definitions from starter.py:
Reject = Tuple[int, str]—(line_index, reason)giving the0-based position of an invalid or conflicting line in its input list alongside a non-empty explanation string.Item(name: str, unit_cents: int, quantity: int, aisle: Optional[int], frozen: bool)— a validated, merged cart product.PricedItem(name: str, quantity: int, full_cents: int, paid_cents: int, promotion: str)— a line item on the checkout receipt.Receipt(item_count: int, subtotal: str, discount: str, total: str, items: List[PricedItem])— the complete checkout summary, with dollar amounts formatted as"D.CC".
Part 1 — Record Parsing and Cart Totals
Implement parse_cart(lines: List[str]) -> Tuple[List[Item], List[Reject]] and cart_totals(lines: List[str]) -> Tuple[int, str]:
- Each cart line must contain five comma-separated fields:
"name,unit_price,quantity,aisle,frozen". Strip leading and trailing whitespace from every field before validating. - Field validation rules:
name: must be non-empty after stripping.unit_price: non-negative dollar value written with plain ASCII digits and an optional decimal point followed by1or2ASCII digits (such as"4","0.8", or"2.45"). Convert directly to exact integerunit_centswithout floating-point rounding. Reject currency symbols, signs, leading decimals like".50", or three-plus decimal places.quantity: positive integer (>= 1) written with plain ASCII digits.aisle: either empty ("", stored asNonefor an unknown aisle) or a non-negative integer (>= 0) written with plain ASCII digits.frozen:"yes"or"no"in any letter case (Truefor"yes",Falsefor"no").
- Any line failing validation is skipped and appended to the returned
Rejectlist with its0-based index. - Merging duplicate product names: Return one
Itemper distinct validname, ordered by first valid appearance. When a later valid line has the samenameand identical(unit_cents, aisle, frozen)attributes, add itsquantityto the existing item. If a later valid line sharesnamewith an earlier item but differs inunit_cents,aisle, orfrozen, reject that later line and leave the earlier item unchanged. cart_totals(lines)returns(total_units, formatted_subtotal)across all valid merged items (for an empty cart,(0, "0.00")).
Part 2 — Best Single-Product Offer at Checkout
Implement checkout(record_lines: List[str], promo_lines: List[str]) -> Receipt:
- Parse
record_linesusingparse_cart(ignoring rejected cart lines). - Strip each line in
promo_linesand recognize two promotion formats targeting a single product<name>(stripped of surrounding spaces, supporting multi-word names):"<name> <P>% off"wherePis an ASCII integer with0 <= P <= 100. Compute the markdown on the product's mergedfull_cents = unit_cents * quantity, rounding once per product to the nearest cent with exact half-cents rounded in the shopper's favor:discount_cents = (full_cents * P + 50) // 100andpaid_cents = full_cents - discount_cents. Its receipt label isf"{P}% off"."<name> buy <N> get <M> free"whereN >= 1andM >= 1are ASCII integers. Partition the product's mergedquantityinto complete groups ofN + Munits (each charging forNunits and givingMfree). Among anyleftover = quantity % (N + M)remaining units, the shopper pays formin(leftover, N)units and receives any additional leftover units free. Its receipt label isf"buy {N} get {M} free".
- Ignore malformed or out-of-range promotion lines (such as
P > 100,N == 0,M == 0, or mismatched keywords/casing) as well as offers for products absent from the cart. - Best-offer and tie-breaking rule: Each product may use at most one promotion — choose the valid promotion for that product yielding the minimum
paid_cents. If no promotion strictly lowerspaid_centsbelowfull_cents, apply none (promotion = ""). If multiple promotions tie for the strictly lowestpaid_cents, keep the one listed earliest inpromo_lines. - Every physical unit in the merged cart (paid or free) counts toward
Receipt.item_count. Formatsubtotal,discount(subtotal - total), andtotalas"D.CC", and preserve first-appearance product order inReceipt.items.
Part 3 — Store-Picking Route Order
Implement order_for_picking(record_lines: List[str]) -> List[str]:
- Parse
record_lineswithparse_cartand return the distinct valid product names sorted for an in-store picker:- All non-frozen items (
frozen == False) come before all frozen items (frozen == True). - Within each temperature section, items with a known numeric
aisleprecede items withaisle is None. - Known aisles are ordered numerically ascending (
2before10). - Remaining ties break lexicographically (
<) byname.
- All non-frozen items (
Examples
Example 1
Input:
record_lines = [
"yogurt,2.45,2,6,no",
"dumplings,5.00,3,11,yes",
"bananas,0.40,5,2,no",
]
promo_lines = [
"yogurt 15% off",
"dumplings 20% off",
"dumplings buy 2 get 1 free",
]
Output:
cart_totals(record_lines) -> (10, "21.90")
checkout(record_lines, promo_lines) -> Receipt(
item_count=10,
subtotal="21.90",
discount="5.74",
total="16.16",
items=[
PricedItem(name="yogurt", quantity=2, full_cents=490, paid_cents=416, promotion="15% off"),
PricedItem(name="dumplings", quantity=3, full_cents=1500, paid_cents=1000, promotion="buy 2 get 1 free"),
PricedItem(name="bananas", quantity=5, full_cents=200, paid_cents=200, promotion=""),
],
)
order_for_picking(record_lines) -> ["bananas", "yogurt", "dumplings"]
Explanation:
The three lines represent 2 + 3 + 5 = 10 units totaling 490 + 1500 + 200 = 2190 cents ("21.90"). At checkout, yogurt saves 15% of 490 cents (73.5 cents rounds to 74 cents in the shopper's favor, leaving 416 cents). For 3 bags of dumplings (1500 cents), "20% off" costs 1200 cents while "buy 2 get 1 free" charges for 2 bags (1000 cents), so "buy 2 get 1 free" wins. For picking, non-frozen bananas (aisle 2) and yogurt (aisle 6) come ahead of frozen dumplings (aisle 11).
Example 2
Input:
record_lines = [
"oatmeal,3.00,2,8,no",
"berries,4.50,1,3,yes",
"oatmeal,3,2,8,NO",
"oatmeal,3.50,1,8,no",
"honey,5.20,1,,no",
"broken_line,1.00",
]
promo_lines = [
"oatmeal buy 2 get 1 free",
"berries buy 2 get 1 free",
]
Output:
parse_cart(record_lines) -> (
[
Item(name="oatmeal", unit_cents=300, quantity=4, aisle=8, frozen=False),
Item(name="berries", unit_cents=450, quantity=1, aisle=3, frozen=True),
Item(name="honey", unit_cents=520, quantity=1, aisle=None, frozen=False),
],
[(3, "..."), (5, "...")],
)
cart_totals(record_lines) -> (6, "21.70")
checkout(record_lines, promo_lines) -> Receipt(
item_count=6,
subtotal="21.70",
discount="3.00",
total="18.70",
items=[
PricedItem(name="oatmeal", quantity=4, full_cents=1200, paid_cents=900, promotion="buy 2 get 1 free"),
PricedItem(name="berries", quantity=1, full_cents=450, paid_cents=450, promotion=""),
PricedItem(name="honey", quantity=1, full_cents=520, paid_cents=520, promotion=""),
],
)
order_for_picking(record_lines) -> ["oatmeal", "honey", "berries"]
Explanation:
Line 2 matches line 0 on unit price (300 cents), aisle (8), and frozen status (False), merging oatmeal to 4 units (1200 cents), while line 3 conflicts on price and line 5 has too few fields. Under "buy 2 get 1 free", 4 units of oatmeal form one group of 3 (2 paid) plus 1 paid leftover (3 paid = 900 cents), whereas 1 bag of berries saves nothing so its promotion label stays "". On the picking route, non-frozen unknown-aisle honey follows aisle-8 oatmeal and still precedes frozen berries (even though berries sit in aisle 3).
Constraints
0 <= len(record_lines), len(promo_lines) <= 10^4- Valid
unit_pricevalues fit in standard integer cents (>= 0) with at most2decimal places. - Valid
quantity >= 1, validaisle >= 0(or empty), valid percentage0 <= P <= 100, and valid group countsN >= 1,M >= 1. - All monetary outputs use exact two-decimal dollar formatting (
"D.CC").
Step-by-step walkthrough
Lock down the input format and business rules
Separating raw text validation from arithmetic keeps every milestone clean:
Cart records: name,unit_price,quantity,aisle,frozen e.g. yogurt,2.45,2,6,no Promotions: <name> <P>% off e.g. yogurt 15% off <name> buy <N> get <M> free e.g. dumplings buy 2 get 1 freeEach policy below locks down an edge case up front:
- Exact money in cents: dollar strings (
"4","0.8","2.45") convert straight to integer cents (400,80,245) without ever touchingfloat. - Malformed records are skipped and reported: invalid field counts, bad prices (
"$1.50","2.455"), zero or non-integer quantities, bad aisles, or invalidfrozenflags return(line_index, reason). An empty aisle ("") is valid and stored asNone. - Repeated products merge quantities: multiple records for
"oatmeal"sum their quantities unless a later record conflicts on price, aisle, or frozen status (in which case that conflicting line is rejected). - Single-product offers, rounded once: each promotion targets one product, percentage discounts round once per product line with exact half cents going to the customer, and free units still count in
item_countbecause they sit in the shopper's bag.
We represent validated items and receipts with named tuples (lightweight, read-only record classes whose fields can be read by clear names like
item.unit_cents):from typing import Dict, List, NamedTuple, Optional, Tuple # Reject: (0-based line index in input list, plain-English rejection reason). Reject = Tuple[int, str] class Item(NamedTuple): name: str unit_cents: int quantity: int aisle: Optional[int] frozen: bool class PricedItem(NamedTuple): name: str quantity: int full_cents: int paid_cents: int promotion: str class Receipt(NamedTuple): item_count: int subtotal: str discount: str total: str items: List[PricedItem]- Exact money in cents: dollar strings (
Convert dollar strings directly to integer cents
Why not convert
"1.15"to cents withint(float("1.15") * 100)? Because binary floating-point numbers cannot represent1.15exactly: in Python,float("1.15") * 100evaluates to114.99999999999999, andint(...)truncates that down to114cents — silently losing a penny!Instead, we match the digits directly using a regular expression (a pattern string that checks whether text follows an exact character structure). Whole dollars multiply by
100, a 1-digit fraction like"0.8"means 8 tenths of a dollar (8 * 10 = 80cents), and a 2-digit fraction like"2.45"adds45cents:import re # Match plain ASCII digits ("0"-"9") so "+2" or "1_000" are rejected cleanly. COUNT = re.compile(r"[0-9]+") # Match whole dollars plus an optional 1- or 2-digit cent fraction, e.g. "4", "0.8", "2.45". PRICE = re.compile(r"([0-9]+)(?:\.([0-9]{1,2}))?") def parse_count(text: str) -> Optional[int]: """Parse a whole number >= 0 written with ASCII digits only, or return None.""" if COUNT.fullmatch(text) is None: return None return int(text) def parse_price(text: str) -> Optional[int]: """Convert a dollar string ('2.45', '4', '0.8') directly to integer cents without floats. Going through float loses cents on binary rounding: int(float('1.15') * 100) is 114! """ match = PRICE.fullmatch(text) if match is None: return None dollars = int(match.group(1)) fraction_digits = match.group(2) # "4" has 0 extra cents; "0.8" means 8 tenths of a dollar = 80 cents; "2.45" has 45 cents. if fraction_digits is None: cents = 0 elif len(fraction_digits) == 1: cents = int(fraction_digits) * 10 else: cents = int(fraction_digits) return dollars * 100 + cents def parse_record(line: str) -> Tuple[Optional[Item], str]: """Validate 'name,unit_price,quantity,aisle,frozen' into (Item, '') or (None, reason).""" fields = [] for raw_field in line.split(","): fields.append(raw_field.strip()) if len(fields) != 5: return None, f"expected 5 fields, got {len(fields)}" name, price_text, quantity_text, aisle_text, frozen_text = fields if name == "": return None, "empty name" unit_cents = parse_price(price_text) if unit_cents is None: return None, "price must look like 2.45" # Every cart line must purchase at least 1 unit. quantity = parse_count(quantity_text) if quantity is None or quantity == 0: return None, "quantity must be a positive whole number" # An empty aisle field is allowed and represented as None ("unknown aisle"). aisle: Optional[int] = None if aisle_text != "": aisle = parse_count(aisle_text) if aisle is None: return None, "aisle must be a whole number or empty" frozen_lower = frozen_text.lower() if frozen_lower not in ("yes", "no"): return None, "frozen must be yes or no" return Item(name, unit_cents, quantity, aisle, frozen_lower == "yes"), ""Part 1: merge repeated products and sum exact cents
parse_cartcollapses repeated lines for the same product into a singleItemright away. That simplifies both Part 2 (promotions see the product's combined cart quantity) and Part 3 (each distinct product appears once on the picking list).def parse_cart(lines: List[str]) -> Tuple[List[Item], List[Reject]]: """Return one merged Item per product name in first-appearance order, plus rejected lines. Repeated lines for the same product sum quantities, while any later line that disagrees on price, aisle, or frozen status is rejected. """ # by_name: dict mapping product name -> merged Item, preserving insertion order. by_name: Dict[str, Item] = {} rejects: List[Reject] = [] for index, line in enumerate(lines): item, reason = parse_record(line) if item is None: rejects.append((index, reason)) continue known = by_name.get(item.name) if known is None: by_name[item.name] = item elif (known.unit_cents, known.aisle, known.frozen) != (item.unit_cents, item.aisle, item.frozen): rejects.append((index, f"conflicts with an earlier record for {item.name}")) else: merged_quantity = known.quantity + item.quantity by_name[item.name] = Item( known.name, known.unit_cents, merged_quantity, known.aisle, known.frozen, ) return list(by_name.values()), rejects def format_dollars(cents: int) -> str: """Format non-negative integer cents as 'D.CC', e.g. 2190 -> '21.90', 5 -> '0.05'.""" dollars = cents // 100 remaining_cents = cents % 100 return f"{dollars}.{remaining_cents:02d}" def cart_totals(lines: List[str]) -> Tuple[int, str]: """Part 1: return (total item count, total price in dollars) across valid cart records.""" items, _ = parse_cart(lines) total_count = 0 total_cents = 0 for item in items: total_count += item.quantity total_cents += item.quantity * item.unit_cents return total_count, format_dollars(total_cents)Part 2: price percentage and buy-N-get-M offers
Offer descriptions like
"20% off"and"buy 2 get 1 free"cannot be ranked by text alone: on 2 bags of dumplings at$5.00,"20% off"saves$2.00while"buy 2 get 1 free"saves$0.00, yet on 3 bags"buy 2 get 1 free"saves$5.00vs.$3.00. Give each promotion type aprice_cents(item)method and compare the resulting cent totals.Buy N get M free: Items form complete groups of
N + Munits, withNpaid andMfree per full group. Anyleftover_unitspast the last full group are paid up toN, and any beyondNare free (min(leftover_units, N)):Offer: buy 2 get 1 free (group_size = 3) quantity = 4: [P P | F] [P] -> 1 full group (2 paid) + min(1, 2) = 3 paid quantity = 5: [P P | F] [P P] -> 1 full group (2 paid) + min(2, 2) = 4 paid Offer: buy 1 get 2 free (group_size = 3, where M > N so min() caps leftovers!) quantity = 5: [P | F F] [P | F] -> 1 full group (1 paid) + min(2, 1) = 2 paidPercentage off:
(full_cents * percent + 50) // 100computes the rounded discount in pure integer math, adding50 / 100 = 0.5cents before floor division so exact half-cent discounts round up in the customer's favor (2yogurts at245cents =490cents with15%off ->(7350 + 50) // 100 = 74cents off ->416cents paid).class PercentOff: """Offer '<name> <P>% off': P% off the product's combined line amount.""" def __init__(self, percent: int): self.percent = percent def price_cents(self, item: Item) -> int: full_cents = item.unit_cents * item.quantity # Add 50 before // 100 to round once per product to nearest cent, half-cent in customer's favor. discount_cents = (full_cents * self.percent + 50) // 100 return full_cents - discount_cents def describe(self) -> str: return f"{self.percent}% off" class BuyNGetMFree: """Offer '<name> buy <N> get <M> free': in each group of N + M units, M are free.""" def __init__(self, buy: int, free: int): self.buy = buy self.free = free def price_cents(self, item: Item) -> int: group_size = self.buy + self.free full_groups = item.quantity // group_size leftover_units = item.quantity % group_size # Leftover units are paid up to N; any leftover units past N (when M > 1) are free. paid_in_leftover = min(leftover_units, self.buy) paid_units = full_groups * self.buy + paid_in_leftover return paid_units * item.unit_cents def describe(self) -> str: return f"buy {self.buy} get {self.free} free"Part 2: parse promotion text and build the receipt
We match promotion strings against a
PROMOTION_FORMATStable of(pattern, builder)pairs. Using a lazy(.+?)capture lets multi-word product names like"ice cream buy 1 get 1 free"parse cleanly, and adding a third offer format later requires only one new class and one table entry without touchingcheckout.In
price_item, starting frombest_cents = full_centsand updating only whencandidate_cents < best_centsguarantees that"no promotion"wins if no offer lowers the price and the earliest offer wins ties.# Lazy (.+?) captures single- or multi-word product names like "ice cream" before the offer suffix. PERCENT_OFF_TEXT = re.compile(r"(.+?)\s+([0-9]+)% off") BUY_GET_TEXT = re.compile(r"(.+?)\s+buy ([0-9]+) get ([0-9]+) free") def build_percent_off(match: re.Match) -> Tuple[Optional[PercentOff], str]: percent = int(match.group(2)) if percent > 100: return None, "a discount cannot exceed 100%" return PercentOff(percent), "" def build_buy_get(match: re.Match) -> Tuple[Optional[BuyNGetMFree], str]: buy = int(match.group(2)) free = int(match.group(3)) if buy == 0 or free == 0: return None, "buy and free counts must be at least 1" return BuyNGetMFree(buy, free), "" # PROMOTION_FORMATS: list of (compiled_regex, builder_fn); new offer types plug in here. PROMOTION_FORMATS = [ (PERCENT_OFF_TEXT, build_percent_off), (BUY_GET_TEXT, build_buy_get), ] def parse_promotions(lines: List[str]) -> Tuple[Dict[str, list], List[Reject]]: """Map each product name to its valid promotion objects in input order, plus rejected lines.""" # by_name: dict mapping product name -> list of promotion objects (PercentOff / BuyNGetMFree). by_name: Dict[str, list] = {} rejects: List[Reject] = [] for index, line in enumerate(lines): text = line.strip() promotion = None reason = "unrecognized promotion" product_name = "" for pattern, build in PROMOTION_FORMATS: match = pattern.fullmatch(text) if match is not None: product_name = match.group(1).strip() if product_name == "": reason = "empty product name" else: promotion, reason = build(match) break if promotion is None: rejects.append((index, reason)) continue if product_name not in by_name: by_name[product_name] = [] by_name[product_name].append(promotion) return by_name, rejects def price_item(item: Item, promotions: list) -> PricedItem: """Choose the single cheapest offer for an item; 'no promotion' wins ties.""" full_cents = item.unit_cents * item.quantity best_cents = full_cents best_label = "" for promotion in promotions: candidate_cents = promotion.price_cents(item) # Strict '<' keeps no-promotion on 0-saving deals and keeps the earliest offer on ties. if candidate_cents < best_cents: best_cents = candidate_cents best_label = promotion.describe() return PricedItem(item.name, item.quantity, full_cents, best_cents, best_label) def checkout(record_lines: List[str], promo_lines: List[str]) -> Receipt: """Part 2: build a Receipt with item count, subtotal, discount, total, and priced lines.""" items, _ = parse_cart(record_lines) promotions_by_name, _ = parse_promotions(promo_lines) priced_items: List[PricedItem] = [] item_count = 0 subtotal_cents = 0 total_cents = 0 for item in items: item_promotions = promotions_by_name.get(item.name, []) priced_line = price_item(item, item_promotions) priced_items.append(priced_line) # Every unit in the cart (paid or free) sits in the shopper's bag and counts in item_count. item_count += item.quantity subtotal_cents += priced_line.full_cents total_cents += priced_line.paid_cents discount_cents = subtotal_cents - total_cents return Receipt( item_count, format_dollars(subtotal_cents), format_dollars(discount_cents), format_dollars(total_cents), priced_items, )Part 3: sort for store picking with a 4-level tuple key
Python sorts tuples using lexicographic comparison: it compares position
0first, moves to position1only on a tie, and so on. Notice whyfrozen_rankMUST sit at position0, even ahead ofmissing_aisle_rank: an item can have an unknown aisle (None) while we still know whether it is frozen! Puttingfrozen_rankfirst guarantees no non-frozen item ever comes after a frozen item:Key shape: (frozen_rank, missing_aisle_rank, numeric_aisle, name) (0, 0, aisle, name) -> 1st: non-frozen, known aisle (aisle 9 before aisle 10, ties by name) (0, 1, 0, name) -> 2nd: non-frozen, unknown aisle (sorted by name, before all frozen items!) (1, 0, aisle, name) -> 3rd: frozen, known aisle (aisle 2 before aisle 12, ties by name) (1, 1, 0, name) -> 4th: frozen, unknown aisle (sorted by name at the very end)def picking_key(item: Item) -> Tuple[int, int, int, str]: """Build 4-part sort key: (frozen_rank, missing_aisle_rank, numeric_aisle, name). Non-frozen items (frozen_rank = 0) always come before frozen items (frozen_rank = 1). Inside each half, known aisles (missing_aisle_rank = 0) come before unknown aisles (1). """ frozen_rank = 1 if item.frozen else 0 if item.aisle is None: return (frozen_rank, 1, 0, item.name) return (frozen_rank, 0, item.aisle, item.name) def order_for_picking(record_lines: List[str]) -> List[str]: """Part 3: return distinct product names in store-picking order.""" items, _ = parse_cart(record_lines) items.sort(key=picking_key) ordered_names: List[str] = [] for item in items: ordered_names.append(item.name) return ordered_namesTrace Example 1 from raw lines to receipt and route
Let's walk Example 1's cart and promotions step by step:
Cart lines: "yogurt,2.45,2,6,no" -> Item("yogurt", 245, 2, 6, False) "dumplings,5.00,3,11,yes" -> Item("dumplings", 500, 3, 11, True) "bananas,0.40,5,2,no" -> Item("bananas", 40, 5, 2, False) Part 1 (Totals): item_count = 2 + 3 + 5 = 10 total_cents = 490 + 1500 + 200 = 2190 -> "21.90" Part 2 (Promotions: "yogurt 15% off", "dumplings 20% off", "dumplings buy 2 get 1 free"): yogurt (full 490): 15% off -> discount (490 * 15 + 50) // 100 = 74 -> paid 416 ("15% off") dumplings (full 1500): 20% off -> 1200 | buy 2 get 1 -> 2 paid = 1000 -> paid 1000 ("buy 2 get 1 free") bananas (full 200): no offers -> paid 200 ("") Receipt: count = 10, subtotal = "21.90", discount = "5.74", total = "16.16" Part 3 (Picking keys): bananas -> (0, 0, 2, "bananas") yogurt -> (0, 0, 6, "yogurt") dumplings -> (1, 0, 11, "dumplings") Order -> ["bananas", "yogurt", "dumplings"]Complete solution
from typing import Dict, List, NamedTuple, Optional, Tuple import re # Reject: (0-based line index in input list, plain-English rejection reason). Reject = Tuple[int, str] # Match plain ASCII digits ("0"-"9") so "+2" or "1_000" are rejected cleanly. COUNT = re.compile(r"[0-9]+") # Match whole dollars plus an optional 1- or 2-digit cent fraction, e.g. "4", "0.8", "2.45". PRICE = re.compile(r"([0-9]+)(?:\.([0-9]{1,2}))?") # Lazy (.+?) captures single- or multi-word product names like "ice cream" before the offer suffix. PERCENT_OFF_TEXT = re.compile(r"(.+?)\s+([0-9]+)% off") BUY_GET_TEXT = re.compile(r"(.+?)\s+buy ([0-9]+) get ([0-9]+) free") class Item(NamedTuple): name: str unit_cents: int quantity: int aisle: Optional[int] frozen: bool class PricedItem(NamedTuple): name: str quantity: int full_cents: int paid_cents: int promotion: str class Receipt(NamedTuple): item_count: int subtotal: str discount: str total: str items: List[PricedItem] # ---------- Part 1: parse records, count items, total price ---------- def parse_count(text: str) -> Optional[int]: """Parse a whole number >= 0 written with ASCII digits only, or return None.""" if COUNT.fullmatch(text) is None: return None return int(text) def parse_price(text: str) -> Optional[int]: """Convert a dollar string ('2.45', '4', '0.8') directly to integer cents without floats. Going through float loses cents on binary rounding: int(float('1.15') * 100) is 114! """ match = PRICE.fullmatch(text) if match is None: return None dollars = int(match.group(1)) fraction_digits = match.group(2) # "4" has 0 extra cents; "0.8" means 8 tenths of a dollar = 80 cents; "2.45" has 45 cents. if fraction_digits is None: cents = 0 elif len(fraction_digits) == 1: cents = int(fraction_digits) * 10 else: cents = int(fraction_digits) return dollars * 100 + cents def parse_record(line: str) -> Tuple[Optional[Item], str]: """Validate 'name,unit_price,quantity,aisle,frozen' into (Item, '') or (None, reason).""" fields = [] for raw_field in line.split(","): fields.append(raw_field.strip()) if len(fields) != 5: return None, f"expected 5 fields, got {len(fields)}" name, price_text, quantity_text, aisle_text, frozen_text = fields if name == "": return None, "empty name" unit_cents = parse_price(price_text) if unit_cents is None: return None, "price must look like 2.45" # Every cart line must purchase at least 1 unit. quantity = parse_count(quantity_text) if quantity is None or quantity == 0: return None, "quantity must be a positive whole number" # An empty aisle field is allowed and represented as None ("unknown aisle"). aisle: Optional[int] = None if aisle_text != "": aisle = parse_count(aisle_text) if aisle is None: return None, "aisle must be a whole number or empty" frozen_lower = frozen_text.lower() if frozen_lower not in ("yes", "no"): return None, "frozen must be yes or no" return Item(name, unit_cents, quantity, aisle, frozen_lower == "yes"), "" def parse_cart(lines: List[str]) -> Tuple[List[Item], List[Reject]]: """Return one merged Item per product name in first-appearance order, plus rejected lines. Repeated lines for the same product sum quantities, while any later line that disagrees on price, aisle, or frozen status is rejected. """ # by_name: dict mapping product name -> merged Item, preserving insertion order. by_name: Dict[str, Item] = {} rejects: List[Reject] = [] for index, line in enumerate(lines): item, reason = parse_record(line) if item is None: rejects.append((index, reason)) continue known = by_name.get(item.name) if known is None: by_name[item.name] = item elif (known.unit_cents, known.aisle, known.frozen) != (item.unit_cents, item.aisle, item.frozen): rejects.append((index, f"conflicts with an earlier record for {item.name}")) else: merged_quantity = known.quantity + item.quantity by_name[item.name] = Item( known.name, known.unit_cents, merged_quantity, known.aisle, known.frozen, ) return list(by_name.values()), rejects def format_dollars(cents: int) -> str: """Format non-negative integer cents as 'D.CC', e.g. 2190 -> '21.90', 5 -> '0.05'.""" dollars = cents // 100 remaining_cents = cents % 100 return f"{dollars}.{remaining_cents:02d}" def cart_totals(lines: List[str]) -> Tuple[int, str]: """Part 1: return (total item count, total price in dollars) across valid cart records.""" items, _ = parse_cart(lines) total_count = 0 total_cents = 0 for item in items: total_count += item.quantity total_cents += item.quantity * item.unit_cents return total_count, format_dollars(total_cents) # ---------- Part 2: promotions, cheapest offer per product ---------- class PercentOff: """Offer '<name> <P>% off': P% off the product's combined line amount.""" def __init__(self, percent: int): self.percent = percent def price_cents(self, item: Item) -> int: full_cents = item.unit_cents * item.quantity # Add 50 before // 100 to round once per product to nearest cent, half-cent in customer's favor. discount_cents = (full_cents * self.percent + 50) // 100 return full_cents - discount_cents def describe(self) -> str: return f"{self.percent}% off" class BuyNGetMFree: """Offer '<name> buy <N> get <M> free': in each group of N + M units, M are free.""" def __init__(self, buy: int, free: int): self.buy = buy self.free = free def price_cents(self, item: Item) -> int: group_size = self.buy + self.free full_groups = item.quantity // group_size leftover_units = item.quantity % group_size # Leftover units are paid up to N; any leftover units past N (when M > 1) are free. paid_in_leftover = min(leftover_units, self.buy) paid_units = full_groups * self.buy + paid_in_leftover return paid_units * item.unit_cents def describe(self) -> str: return f"buy {self.buy} get {self.free} free" def build_percent_off(match: re.Match) -> Tuple[Optional[PercentOff], str]: percent = int(match.group(2)) if percent > 100: return None, "a discount cannot exceed 100%" return PercentOff(percent), "" def build_buy_get(match: re.Match) -> Tuple[Optional[BuyNGetMFree], str]: buy = int(match.group(2)) free = int(match.group(3)) if buy == 0 or free == 0: return None, "buy and free counts must be at least 1" return BuyNGetMFree(buy, free), "" # PROMOTION_FORMATS: list of (compiled_regex, builder_fn); new offer types plug in here. PROMOTION_FORMATS = [ (PERCENT_OFF_TEXT, build_percent_off), (BUY_GET_TEXT, build_buy_get), ] def parse_promotions(lines: List[str]) -> Tuple[Dict[str, list], List[Reject]]: """Map each product name to its valid promotion objects in input order, plus rejected lines.""" # by_name: dict mapping product name -> list of promotion objects (PercentOff / BuyNGetMFree). by_name: Dict[str, list] = {} rejects: List[Reject] = [] for index, line in enumerate(lines): text = line.strip() promotion = None reason = "unrecognized promotion" product_name = "" for pattern, build in PROMOTION_FORMATS: match = pattern.fullmatch(text) if match is not None: product_name = match.group(1).strip() if product_name == "": reason = "empty product name" else: promotion, reason = build(match) break if promotion is None: rejects.append((index, reason)) continue if product_name not in by_name: by_name[product_name] = [] by_name[product_name].append(promotion) return by_name, rejects def price_item(item: Item, promotions: list) -> PricedItem: """Choose the single cheapest offer for an item; 'no promotion' wins ties.""" full_cents = item.unit_cents * item.quantity best_cents = full_cents best_label = "" for promotion in promotions: candidate_cents = promotion.price_cents(item) # Strict '<' keeps no-promotion on 0-saving deals and keeps the earliest offer on ties. if candidate_cents < best_cents: best_cents = candidate_cents best_label = promotion.describe() return PricedItem(item.name, item.quantity, full_cents, best_cents, best_label) def checkout(record_lines: List[str], promo_lines: List[str]) -> Receipt: """Part 2: build a Receipt with item count, subtotal, discount, total, and priced lines.""" items, _ = parse_cart(record_lines) promotions_by_name, _ = parse_promotions(promo_lines) priced_items: List[PricedItem] = [] item_count = 0 subtotal_cents = 0 total_cents = 0 for item in items: item_promotions = promotions_by_name.get(item.name, []) priced_line = price_item(item, item_promotions) priced_items.append(priced_line) # Every unit in the cart (paid or free) sits in the shopper's bag and counts in item_count. item_count += item.quantity subtotal_cents += priced_line.full_cents total_cents += priced_line.paid_cents discount_cents = subtotal_cents - total_cents return Receipt( item_count, format_dollars(subtotal_cents), format_dollars(discount_cents), format_dollars(total_cents), priced_items, ) # ---------- Part 3: order by aisle, frozen items last ---------- def picking_key(item: Item) -> Tuple[int, int, int, str]: """Build 4-part sort key: (frozen_rank, missing_aisle_rank, numeric_aisle, name). Non-frozen items (frozen_rank = 0) always come before frozen items (frozen_rank = 1). Inside each half, known aisles (missing_aisle_rank = 0) come before unknown aisles (1). """ frozen_rank = 1 if item.frozen else 0 if item.aisle is None: return (frozen_rank, 1, 0, item.name) return (frozen_rank, 0, item.aisle, item.name) def order_for_picking(record_lines: List[str]) -> List[str]: """Part 3: return distinct product names in store-picking order.""" items, _ = parse_cart(record_lines) items.sort(key=picking_key) ordered_names: List[str] = [] for item in items: ordered_names.append(item.name) return ordered_names✅ Submit now — all tests should pass.
Intuition & how it works
Imagine building both a grocery store's checkout register and its personal-shopper route planner. At the front door, parse_cart converts messy comma-separated strings into clean, merged Item named tuples (lightweight, read-only objects with named fields) whose prices are stored in whole integer cents. At the register, every promotion class answers one simple question — "how many cents would this product cost under me?" — so picking the best deal is just taking the minimum price. Finally, the shopper route sorts items in one pass using a 4-part composite sort key (a tuple compared from left to right) so frozen items are always picked last before heading to the register.
Naive shortcuts fail in subtle ways on all three parts. Converting "1.15" via int(float("1.15") * 100) yields 114 cents because binary floating-point stores 1.15 * 100 as 114.99999999999999. Ranking offers by their text alone fails because "20% off" beats "buy 2 get 1 free" on 2 bags of dumplings at $5.00 ($8.00 vs. $10.00), whereas "buy 2 get 1 free" wins on 3 bags ($10.00 vs. $12.00). And throwing all missing-aisle items blindly at the very end of the picking list puts non-frozen unknown-aisle items after frozen items, letting frozen food thaw.
Here is how Example 1's cart flows through all three steps:
- Part 1 (Merge & Total):
"yogurt,2.45,2,6,no"(490cents),"dumplings,5.00,3,11,yes"(1500cents), and"bananas,0.40,5,2,no"(200cents) sum to2 + 3 + 5 = 10items and2190cents ("21.90"). - Part 2 (Best Offer per Product):
yogurtgets15% off(74cents off ->416cents);dumplingscompares20% off(1200cents) againstbuy 2 get 1 free(1000cents) and picks1000;bananasstay200cents, producing total"16.16"and discount"5.74". - Part 3 (Picking Order): keys
(0, 0, 2, "bananas"),(0, 0, 6, "yogurt"), and(1, 0, 11, "dumplings")sort cleanly into["bananas", "yogurt", "dumplings"].
Complexity
- Part 1 — Time O(C), Space O(p): we scan the
Cinput characters once, splitting each record on","and merging repeated names in a dictionary in O(1) time per record. Storing one mergedItemfor each of thepdistinct products takes O(p) space (plus one entry per rejected line). - Part 2 — Time O(C + P), Space O(p + q): scanning
Pcharacters of promotion lines matches each line against a constant number of regular expressions (character pattern matchers) to buildqpromotion objects, and each promotion evaluates in O(1) integer arithmetic. Storing thepreceipt lines andqpromotions uses O(p + q) memory. - Part 3 — Time O(C + p log p), Space O(p): after parsing the
pdistinct products in O(C) time, sorting them withpicking_keyruns O(p log p) comparisons on 4-element tuples and returns an O(p) list of product names.
Edge cases
- Empty cart: returns
(0, "0.00")for totals,Receipt(0, "0.00", "0.00", "0.00", [])for checkout, and[]for picking order. - Varied valid and invalid price strings:
"4"(400cents),"0.8"(80cents), and"2.45"(245cents) parse cleanly, while"2.455","$1.50",".50", and"-1.00"are rejected. - Repeated product records: identical attributes merge by summing quantities; any record that disagrees with an earlier price, aisle, or frozen flag for the same product name is rejected.
- Leftover units in buy-N-get-M: under
buy 1 get 2 freeon 5 units (1full group of3+2leftovers),min(leftover_units, N) = min(2, 1) = 1ensures the 2nd leftover unit is free (2units paid total). - Missing aisles in both sections: an empty aisle field (
"") becomesNone; non-frozen unknown-aisle items ((0, 1, 0, name)) stay ahead of all frozen items ((1, ...)), and frozen unknown-aisle items ((1, 1, 0, name)) sit at the very end. - Multi-word product names:
"ice cream buy 1 get 1 free"parses"ice cream"accurately via the lazy(.+?)capture.
Common mistakes
- Parsing dollar strings with
float():int(float("1.15") * 100)truncates to114cents instead of115; always parse whole dollars and cent digits directly as integers. - Rounding percentages per unit instead of per product line: 3 mints at
$0.05(15cents total) with10% offgive a1.5-cent discount ->2cents off (13cents paid) when rounded once per product, whereas rounding each unit's0.5-cent discount separately would give3cents off (12cents paid). - Evaluating promotions before merging duplicate product lines: keeping two
"oatmeal"lines of2and2separate prevents all4units from pooling together under"buy 2 get 1 free". - Sorting aisles as strings: string comparison puts
"10"before"9". - Breaking the frozen-last invariant on missing aisles: placing all
aisle is Noneitems in a single bucket at the very end puts non-frozen unknown-aisle items after frozen ones;frozen_rankmust be the very first tuple field.
Follow-up questions
- Suppose you introduce multi-item bundle deals across distinct products, like buying any three eligible snacks for a flat dollar amount. Why does picking the lowest price independently per product fail? Because each physical unit can participate in only one promotion, assigning units of product A to a cross-product bundle changes how many units remain for product A's own single-product discount (and affects whether products B and C can complete a bundle). For example, 2 bags of chips at
$2.50plus 1 soda at$2.00under"any 3 snacks for $5.00"beats"chips 10% off"($4.50 + $2.00 = $6.50), yet loses if chips also have"buy 1 get 1 free"($2.50 + $2.00 = $4.50). Finding the true minimum cart price requires optimizing across the group jointly using dynamic programming (caching optimal sub-cart prices indexed by product index and bundle slots filled) rather than greedy per-product choices. - If a product can combine a percentage markdown with a buy-N-get-M-free deal, which promotion should run first, and can changing that sequence alter the final cent total? Yes, both the base definition and integer rounding can change the final cent amount. If both discounts were computed independently off the full price ("additive stacking"), 3 bags of dumplings at
$5.00($15.00) withbuy 2 get 1(-$5.00) and20% off(-$3.00) would drop to$7.00, whereas taking free units first ($10.00) and applying20% offto the remaining paid amount ("multiplicative stacking") gives$8.00— and even under multiplicative stacking, rounding per unit vs. once per line can differ by a cent (3items at$0.15withbuy 2 get 1and10% offis30 - 3 = 27cents rounded once vs.2 * (15 - 2) = 26cents rounded per unit). The standard retail rule is to remove free units first and apply the percentage once to the remaining paid cents. - When catalog entries omit an aisle number, how should the picker's route position them, and how would a production system surface the missing data? Using
(frozen_rank, missing_aisle_rank, numeric_aisle, name)places non-frozen unknown-aisle items right after known non-frozen aisles (before the shopper opens any freezer door) and frozen unknown-aisle items at the very end of the trip, preserving food safety even with incomplete catalog data. In production, return missing-aisle items in a dedicated warning section on the picker's screen and emit a catalog-quality alert logging those product names so store ops can fill in their aisle numbers. - What testing strategy ensures that registering a brand-new promotion format never accidentally alters how existing offers price a cart? Combine three layers of automated tests: unit tests per promotion class covering boundary quantities (
N - 1,N,N + M, leftovers,0%,100%, half-cent ties), golden snapshot receipts verified by hand on carts using only existing offer types (which must stay byte-for-byte identical when a new class is registered inPROMOTION_FORMATS), and property-based testing (running hundreds of randomly generated carts against a slow, dead-simple unit-by-unitFractionsimulator while asserting universal invariants like0 <= paid_cents <= full_cents).
Follow-up questions
- Suppose you introduce multi-item bundle deals across distinct products, like buying any three eligible snacks for a flat dollar amount. Why does picking the lowest price independently per product fail?
- If a product can combine a percentage markdown with a buy-N-get-M-free deal, which promotion should run first, and can changing that sequence alter the final cent total?
- When catalog entries omit an aisle number, how should the picker's route position them, and how would a production system surface the missing data?
- What testing strategy ensures that registering a brand-new promotion format never accidentally alters how existing offers price a cart?
Similar questions
- Catalog Search, Filtering, and Pagination
- Library Hold-Queue and Loan Reminder Notification Manager
- Fix Pre-Filter Summary Totals in a Reporting API
- Debugging Catalog Search Gaps and Inventory State Bugs
- Transit Simulation Efficiency Metric
- Priority Task Assignment System
More Instacart interview questions
- Debugging Catalog Search Gaps and Inventory State Bugs Easy
- Multi-Stage Cart Pricing, Best-Offer Selection, and Aisle Picking Medium
- Inventory Reservations, Hot-SKU Scaling, and Oversell Control Medium Pro
- Multi-Location Inventory and Order-Picking System Medium Pro
- Resolve Target Variable Across Additive Assignment Chains Medium Pro
- Precedence-Aware Expression Evaluator Medium Pro
- Diagnosing a Marketplace KPI Drop Easy Pro
- Marketplace KPI Triage, Geo-Testing, and Retention Easy Pro
- Catalog Search, Filtering, and Pagination Medium Pro
- Library Hold-Queue and Loan Reminder Notification Manager Medium Pro