Multi-Stage Cart Pricing, Best-Offer Selection, and Aisle Picking

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build a three-stage grocery cart processor that validates pipe-delimited (|) text records in integer cents, selects the lowest-cost single promotion per SKU, and orders cart items into a store-picking route. Surrounding spaces on every pipe-separated field are trimmed (field.strip()), and malformed records must be skipped cleanly rather than crashing the calculation.

Stage 1 — Order Line Validation and Cart Totals

Each order record has four fields: SKUid|SKUNAME|QUANTITY|Price, where Price is the single-unit price in integer cents.

  • parse_order_lines(lines: List[str]) -> Tuple[List[OrderLine], List[Reject]]: Return (valid_records, rejected_records) in input order, where OrderLine(sku, name, quantity, unit_cents) holds validated fields and each Reject is (line_index, reason) using 0-based indices. Reject any line that:
    • does not contain 4 pipe-separated fields,
    • has an empty SKUid after trimming,
    • has a QUANTITY that is not composed solely of ASCII digits [0-9]+ with value >= 1 (signs, decimals, and underscores are invalid),
    • has a Price that is not composed solely of ASCII digits [0-9]+ with value >= 0 (0 cents is valid), or
    • specifies a different unit price than an earlier valid line for the same SKUid (repeated lines for the same SKUid at the same unit price are valid and accumulate quantity).
  • order_totals(lines: List[str]) -> Tuple[int, str]: Return (total_quantity, dollar_string) across all valid lines, formatting total cents with two decimal places ("D.CC", such as "0.00" or "20.99").

Stage 2 — Per-SKU Promotions

Promotions arrive in a separate promo_lines: List[str] using two deal codes:

  • SKUid|axf|P — Percentage markdown of P% (P is an ASCII-digit integer 0 <= P <= 100), labeled f"{P}% off". Compute the discount once on the SKU's combined cart subtotal (full_cents = combined_quantity * unit_cents), rounding to the nearest cent with exact half-cents (0.5) rounded up in the shopper's favor (discount = (full_cents * P + 50) // 100).
  • SKUid|bxf|X|Y — Bundle freebie (X and Y are ASCII-digit integers >= 1), labeled f"buy {X} get {Y} free". Evaluated on the SKU's combined cart quantity (without adding extra items): in every complete group of X + Y units, X units are paid and Y units are free; in an incomplete remainder of r units, min(r, X) units are paid and any units beyond X are free.

Malformed promotion lines, unknown deal codes, and promotions for SKUs not in the valid cart are ignored. Deals do not stack: for each distinct ordered SKU, compare the un-discounted baseline (combined_quantity * unit_cents, label "") against every valid deal for that SKU and choose the strictly lowest cent cost ("" wins ties at full price; among tied discounted deals, the earliest line in promo_lines wins).

  • best_prices(order_lines: List[str], promo_lines: List[str]) -> Dict[str, Tuple[int, str]]: Map each distinct valid ordered SKU to (post_promo_cents, winning_label_or_empty).
  • totals_after_promotions(order_lines: List[str], promo_lines: List[str]) -> Tuple[int, str]: Return (total_quantity, dollar_string) after applying each SKU's best deal (total_quantity still counts all physical units in the valid cart).

Stage 3 — Store Aisle Picking Sequence

Store locations arrive in location_lines: List[str] formatted SKUid|aisle|isFrozen:

  • Valid lines have 3 fields, non-empty SKUid, aisle composed of ASCII digits [0-9]+ (>= 0), and isFrozen matching "true" or "false" (case-insensitive). Malformed lines are ignored; if a SKU has multiple valid location lines, its first valid location wins.
  • aisle_order(order_lines: List[str], location_lines: List[str]) -> List[str]: Return the distinct valid ordered SKUids sorted so that:
    1. Non-frozen SKUs come first in ascending numeric aisle order.
    2. Frozen SKUs come next (after all non-frozen SKUs) in ascending numeric aisle order.
    3. Ordered SKUs with no valid location come last.
    4. Ties within any section break in ascending ASCII order of SKUid.

Examples

Example 1 — Parsing and Cart Totals

orders = [
    "OAT|Rolled Oats|6|150",
    "YOG|Greek Yogurt|3|200",
    "PEAS|Frozen Peas|1|449",
    "ERR1|Bad Qty|two|150",
    "ERR2|Missing Price|4",
    "OAT|Rolled Oats|1|150",
]

order_totals(orders)
# -> (11, "20.99")

Walk-through: Lines 3 ("two" is non-numeric) and 4 (only 3 fields) are rejected. The four valid lines yield 6 + 3 + 1 + 1 = 11 units and 900 + 600 + 449 + 150 = 2099 cents ("20.99"), with both "OAT" lines sharing the 150-cent unit price.

Example 2 — Cheapest Deal per SKU

promos = ["OAT|axf|20", "OAT|bxf|4|2", "YOG|axf|15", "PEAS|bxf|2|1"]

best_prices(orders, promos)
# -> {"OAT": (750, "buy 4 get 2 free"), "YOG": (510, "15% off"), "PEAS": (449, "")}

totals_after_promotions(orders, promos)
# -> (11, "17.09")

Walk-through: "OAT" combines to 7 units (1050 cents): "20% off" costs 840 cents, whereas "buy 4 get 2 free" forms one full group of 6 (4 paid) plus 1 leftover (1 paid) = 5 * 150 = 750 cents, so "buy 4 get 2 free" wins. "YOG" (600 cents) drops by 15% (90 cents) to 510 cents. "PEAS" has only 1 unit, so "buy 2 get 1 free" saves 0 cents and the un-discounted baseline "" keeps the tie (449 cents). Summing 750 + 510 + 449 = 1709 cents gives "17.09".

Example 3 — Store Picking Order

places = ["YOG|12|false", "OAT|4|false", "PEAS|2|true"]

aisle_order(orders, places)
# -> ["OAT", "YOG", "PEAS"]

Walk-through: Non-frozen "OAT" (aisle 4) precedes non-frozen "YOG" (aisle 12) under numeric comparison (4 < 12), while frozen "PEAS" is placed after all non-frozen items despite sitting in aisle 2.

Constraints

  • Keep all monetary calculations in exact integer cents, formatting into "D.CC" only when producing output strings.
  • Numeric fields (QUANTITY, Price, P, X, Y, aisle) accept plain ASCII digits [0-9]+ only (after trimming surrounding spaces).
  • Structure promotion parsing so additional deal codes can be registered without rewriting the per-SKU pricing loop.

Step-by-step walkthrough

  1. Clarify the rules and define typed records

    Before writing parsing code, make sure Stage 1, Stage 2, and Stage 3 share one consistent set of contracts:

    • Three separate input lists: order lines, promotion lines, and location lines arrive as separate lists of strings.
    • Unit price in integer cents: in OAT|Rolled Oats|6|150, 150 is the price of one unit (150 cents = $1.50), matching the sample total (6 + 1) * 150 + 3 * 200 + 1 * 449 = 2099 cents ("20.99").
    • Skip and report malformed lines: bad lines never crash the cart processor. Instead, each parser returns valid records alongside (line_index, reason) pairs so callers can inspect or log rejected rows.
    • Repeated SKUs add quantities, while conflicting prices reject: when OAT appears twice at 150 cents, the quantities sum (6 + 1 = 7); if a later line gives OAT a different unit price, that conflicting line is rejected so every SKU has one unambiguous unit price.

    We model validated data with two named tuples (lightweight, read-only record classes whose fields can be accessed by clear names like record.sku instead of numeric indices):

    from typing import Dict, List, NamedTuple, Optional, Tuple
    
    # Reject: (0-based line index in input list, plain-English rejection reason), e.g. (3, "empty SKU id").
    Reject = Tuple[int, str]
    
    
    class OrderLine(NamedTuple):
        sku: str
        name: str
        quantity: int
        unit_cents: int
    
    
    class Location(NamedTuple):
        aisle: int
        frozen: bool
    
  2. Validate each order line strictly

    Separating line validation from math ensures the totals functions only ever touch clean, typed OrderLine objects.

    Why not validate numbers by wrapping Python's int(text) in try / except? Because int() is surprisingly permissive: int("+7") returns 7 and int("1_000") returns 1000. Instead, we use a regular expression (a pattern string that checks whether text matches an exact character rule) [0-9]+ so only plain ASCII digits pass:

    import re
    
    # Match one or more plain ASCII digits ("0"-"9") with no signs, spaces, or underscores.
    DIGITS = re.compile(r"[0-9]+")
    
    
    def split_fields(line: str) -> List[str]:
        """Split a pipe-delimited line and trim surrounding spaces from every field."""
        fields = []
        for raw_field in line.split("|"):
            fields.append(raw_field.strip())
        return fields
    
    
    def parse_count(text: str) -> Optional[int]:
        """Parse a whole number >= 0 written with ASCII digits only, or return None.
    
        Python's built-in int() is too lenient on its own because it accepts "+7" and "1_000".
        """
        if DIGITS.fullmatch(text) is None:
            return None
        return int(text)
    
    
    def parse_order_line(line: str) -> Tuple[Optional[OrderLine], str]:
        """Validate one 'SKUid|SKUNAME|QUANTITY|Price' line into (OrderLine, '') or (None, reason)."""
        fields = split_fields(line)
        if len(fields) != 4:
            return None, f"expected 4 fields, got {len(fields)}"
    
        sku, name, quantity_text, price_text = fields
        if sku == "":
            return None, "empty SKU id"
    
        # Quantity must be a whole number >= 1 because ordering 0 items is meaningless.
        quantity = parse_count(quantity_text)
        if quantity is None or quantity == 0:
            return None, "quantity must be a positive whole number"
    
        # Unit price can be 0 (a free item), so any whole number >= 0 is valid.
        unit_cents = parse_count(price_text)
        if unit_cents is None:
            return None, "price must be a whole number of cents"
    
        return OrderLine(sku, name, quantity, unit_cents), ""
    

    On Example 1, ERR1|Bad Qty|two|150 fails parse_count("two") and ERR2|Missing Price|4 fails len(fields) != 4, returning (None, reason) cleanly.

  3. Stage 1: merge valid lines and sum integer cents

    Never store money in binary floating-point numbers (float): in Python, 0.10 + 0.20 evaluates to 0.30000000000000004 because 0.1 and 0.2 have repeating binary expansions. Keeping every amount in integer cents makes addition exact for any cart size. We divide by 100 only once at the very end when formatting "D.CC".

    def parse_order_lines(lines: List[str]) -> Tuple[List[OrderLine], List[Reject]]:
        """Return valid order lines in input order, plus rejected (index, reason) pairs.
    
        A SKU locks in the unit price of its first valid line; any later line for the
        same SKU with a different unit price is rejected so per-SKU pricing is unambiguous.
        """
        valid: List[OrderLine] = []
        rejects: List[Reject] = []
        # price_of_sku: dict mapping sku -> unit_cents from its first valid line, e.g. {"OAT": 150}.
        price_of_sku: Dict[str, int] = {}
    
        for index, line in enumerate(lines):
            record, reason = parse_order_line(line)
            if record is None:
                rejects.append((index, reason))
                continue
    
            known_price = price_of_sku.get(record.sku)
            if known_price is not None and known_price != record.unit_cents:
                rejects.append((index, f"price conflicts with an earlier line for {record.sku}"))
                continue
    
            price_of_sku[record.sku] = record.unit_cents
            valid.append(record)
    
        return valid, rejects
    
    
    def format_dollars(cents: int) -> str:
        """Format non-negative integer cents as 'D.CC', e.g. 2099 -> '20.99', 5 -> '0.05'."""
        dollars = cents // 100
        remaining_cents = cents % 100
        # ':02d' pads single-digit cents with a leading zero so 5 cents formats as "0.05", not "0.5".
        return f"{dollars}.{remaining_cents:02d}"
    
    
    def order_totals(lines: List[str]) -> Tuple[int, str]:
        """Part 1: return (total quantity, total price in dollars) across all valid order lines."""
        records, _ = parse_order_lines(lines)
        total_quantity = 0
        total_cents = 0
        for record in records:
            total_quantity += record.quantity
            total_cents += record.quantity * record.unit_cents
        return total_quantity, format_dollars(total_cents)
    
  4. Stage 2: compute exact promotion prices

    You cannot tell whether "20% off" beats "buy 4 get 2 free" from the deal text alone — for 4 units "20% off" is cheaper (480 vs. 600 cents at $1.50 each), whereas for 6 or 7 units "buy 4 get 2 free" is cheaper (600 or 750 vs. 720 or 840 cents). Give every promotion class the same price_cents(quantity, unit_cents) method so comparing deals reduces to comparing integer prices.

    Percentage discount (axf) with integer round-half-up: For full_cents at percent% off, the exact discount in cents is (full_cents * percent) / 100. To round to the nearest cent with an exact 0.5 cent going to the customer (rounding the discount up), add 0.5 (50 / 100) before flooring:

    discount_cents = (full_cents * percent + 50) // 100
    
    Example: 1 item at 5 cents with 10% off -> exact discount = 0.50 cents
      (5 * 10 + 50) // 100 = 100 // 100 = 1 cent discount -> customer pays 4 cents
    

    Notice why we avoid Python's built-in round(): round(0.5) rounds to even (0), which would shortchange the customer by a cent.

    Buy X get Y free (bxf): Items in the cart form complete groups of X + Y units; inside each full group the customer pays for X units and gets Y units free. In a leftover partial group of leftover_units, the customer pays for the first X units and any units beyond X are free (min(leftover_units, X)):

    Offer: buy 4 get 2 free (group_size = 4 + 2 = 6)
    
    quantity = 5:  [P P P P | F]                  -> 0 full groups, leftover 5 -> min(5, 4) = 4 paid
    quantity = 6:  [P P P P | F F]                -> 1 full group,  leftover 0 -> 4 + 0     = 4 paid
    quantity = 7:  [P P P P | F F] [P]            -> 1 full group,  leftover 1 -> 4 + 1     = 5 paid
    quantity = 13: [P P P P | F F] [P P P P | F F] [P] -> 2 full,   leftover 1 -> 8 + 1     = 9 paid
    
    class PercentOff:
        """Promotion 'SKU|axf|P': P% off the SKU's combined line amount."""
    
        def __init__(self, percent: int):
            self.percent = percent
    
        def price_cents(self, quantity: int, unit_cents: int) -> int:
            full_cents = quantity * unit_cents
            # Adding 50 before integer division by 100 rounds >= 0.5 cents up in the customer's favor.
            discount_cents = (full_cents * self.percent + 50) // 100
            return full_cents - discount_cents
    
        def label(self) -> str:
            return f"{self.percent}% off"
    
    
    class BuyXGetYFree:
        """Promotion 'SKU|bxf|X|Y': in every group of X + Y units, Y units are free."""
    
        def __init__(self, buy: int, free: int):
            self.buy = buy
            self.free = free
    
        def price_cents(self, quantity: int, unit_cents: int) -> int:
            group_size = self.buy + self.free
            full_groups = quantity // group_size
            leftover_units = quantity % group_size
            # In an incomplete group, the customer pays for at most X units and any extras beyond X are free.
            paid_in_leftover = min(leftover_units, self.buy)
            paid_units = full_groups * self.buy + paid_in_leftover
            return paid_units * unit_cents
    
        def label(self) -> str:
            return f"buy {self.buy} get {self.free} free"
    
  5. Stage 2: register promotion parsers and pick the cheapest deal

    To make new promotion types easy to add without editing the checkout loop, dispatch promotion type codes through a PROMOTION_PARSERS dictionary. Adding a future "fixed_off" deal will only require one new class and one dictionary entry.

    Before pricing promotions, group_by_sku sums quantities across all valid order lines for the same SKU so 6 units of "OAT" on line 0 plus 1 unit on line 5 combine into 7 units for "buy 4 get 2 free". Then best_price starts from the un-discounted baseline (quantity * unit_cents, "") and updates only on strict <, so "no promotion" wins if no deal saves money and the first listed deal wins ties.

    def parse_percent_off(values: List[str]) -> Tuple[Optional[PercentOff], str]:
        if len(values) != 1:
            return None, "axf takes one value"
        percent = parse_count(values[0])
        if percent is None or percent > 100:
            return None, "percent must be a whole number from 0 to 100"
        return PercentOff(percent), ""
    
    
    def parse_buy_x_get_y(values: List[str]) -> Tuple[Optional[BuyXGetYFree], str]:
        if len(values) != 2:
            return None, "bxf takes two values"
        buy = parse_count(values[0])
        free = parse_count(values[1])
        if buy is None or free is None or buy == 0 or free == 0:
            return None, "buy and free counts must be positive whole numbers"
        return BuyXGetYFree(buy, free), ""
    
    
    # PROMOTION_PARSERS: registry mapping promo type code -> parser function; new deals plug in here.
    PROMOTION_PARSERS = {
        "axf": parse_percent_off,
        "bxf": parse_buy_x_get_y,
    }
    
    
    def parse_promotions(lines: List[str]) -> Tuple[Dict[str, list], List[Reject]]:
        """Group valid promotion objects by SKU in input order, plus rejected (index, reason) pairs."""
        # by_sku: dict mapping sku -> list of promotion objects (PercentOff / BuyXGetYFree) in input order.
        by_sku: Dict[str, list] = {}
        rejects: List[Reject] = []
    
        for index, line in enumerate(lines):
            fields = split_fields(line)
            if len(fields) < 2 or fields[0] == "":
                rejects.append((index, "expected SKUid|type|values"))
                continue
    
            sku = fields[0]
            promo_type = fields[1]
            parser = PROMOTION_PARSERS.get(promo_type)
            if parser is None:
                rejects.append((index, f"unknown promotion type {promo_type!r}"))
                continue
    
            promotion, reason = parser(fields[2:])
            if promotion is None:
                rejects.append((index, reason))
                continue
    
            if sku not in by_sku:
                by_sku[sku] = []
            by_sku[sku].append(promotion)
    
        return by_sku, rejects
    
    
    def group_by_sku(records: List[OrderLine]) -> Dict[str, Tuple[int, int]]:
        """Combine multiple lines for the same SKU into {sku: (combined_quantity, unit_cents)}."""
        # groups: dict mapping sku -> (combined_quantity, unit_cents) in first-appearance order.
        groups: Dict[str, Tuple[int, int]] = {}
        for record in records:
            if record.sku not in groups:
                groups[record.sku] = (record.quantity, record.unit_cents)
            else:
                old_quantity, unit_cents = groups[record.sku]
                groups[record.sku] = (old_quantity + record.quantity, unit_cents)
        return groups
    
    
    def best_price(quantity: int, unit_cents: int, promotions: list) -> Tuple[int, str]:
        """Return (lowest_cents, winning_label) for one SKU; 'no promotion' wins ties."""
        best_cents = quantity * unit_cents
        best_label = ""
        for promotion in promotions:
            candidate_cents = promotion.price_cents(quantity, unit_cents)
            # Strict '<' ensures no-promotion wins ties at full price and earlier promos win equal deals.
            if candidate_cents < best_cents:
                best_cents = candidate_cents
                best_label = promotion.label()
        return best_cents, best_label
    
    
    def best_prices(order_lines: List[str], promo_lines: List[str]) -> Dict[str, Tuple[int, str]]:
        """Part 2: return {sku: (cents_after_best_promotion, label_or_empty)}."""
        records, _ = parse_order_lines(order_lines)
        promotions_by_sku, _ = parse_promotions(promo_lines)
        result: Dict[str, Tuple[int, str]] = {}
        for sku, (quantity, unit_cents) in group_by_sku(records).items():
            sku_promotions = promotions_by_sku.get(sku, [])
            result[sku] = best_price(quantity, unit_cents, sku_promotions)
        return result
    
    
    def totals_after_promotions(order_lines: List[str], promo_lines: List[str]) -> Tuple[int, str]:
        """Part 2: return (total quantity, total price in dollars after best promotion per SKU)."""
        records, _ = parse_order_lines(order_lines)
        promotions_by_sku, _ = parse_promotions(promo_lines)
        sku_groups = group_by_sku(records)
    
        total_quantity = 0
        total_cents = 0
        for sku, (quantity, unit_cents) in sku_groups.items():
            # Every physical unit in the cart counts toward total_quantity, even if a promotion makes it free.
            total_quantity += quantity
            sku_promotions = promotions_by_sku.get(sku, [])
            discounted_cents, _ = best_price(quantity, unit_cents, sku_promotions)
            total_cents += discounted_cents
    
        return total_quantity, format_dollars(total_cents)
    
  6. Stage 3: sort SKUs with a single composite tuple key

    Python compares tuples using lexicographic comparison: it compares the first elements, only checks the second elements if the first elements tie, and only checks the third elements if the second elements also tie.

    That lets us express every picking rule inside a single 3-tuple (section_rank, numeric_aisle, sku_id):

    Sort key shape: (section_rank, numeric_aisle, sku_id)
    
      section_rank = 0  -> non-frozen items, ordered by integer aisle (4 before 12), ties broken by SKU
      section_rank = 1  -> frozen items,     ordered by integer aisle (2 before 10), ties broken by SKU
      section_rank = 2  -> missing location, aisle = 0, ordered by SKU at the very end
    

    Why store aisle as an int? Because string comparison compares character by character ("12" < "4" since '1' < '4'), whereas integer comparison puts aisle 4 before aisle 12.

    def parse_location_line(line: str) -> Tuple[Optional[Tuple[str, Location]], str]:
        """Validate one 'SKUid|aisle|isFrozen' line into ((sku, Location), '') or (None, reason)."""
        fields = split_fields(line)
        if len(fields) != 3:
            return None, f"expected 3 fields, got {len(fields)}"
    
        sku, aisle_text, frozen_text = fields
        if sku == "":
            return None, "empty SKU id"
    
        aisle = parse_count(aisle_text)
        if aisle is None:
            return None, "aisle must be a whole number"
    
        frozen_lower = frozen_text.lower()
        if frozen_lower not in ("true", "false"):
            return None, "isFrozen must be true or false"
    
        return (sku, Location(aisle, frozen_lower == "true")), ""
    
    
    def parse_locations(lines: List[str]) -> Tuple[Dict[str, Location], List[Reject]]:
        """Map each SKU to its first valid Location; reject conflicting later locations."""
        # locations: dict mapping sku -> Location(aisle, frozen), e.g. {"OAT": Location(4, False)}.
        locations: Dict[str, Location] = {}
        rejects: List[Reject] = []
    
        for index, line in enumerate(lines):
            parsed, reason = parse_location_line(line)
            if parsed is None:
                rejects.append((index, reason))
                continue
    
            sku, location = parsed
            # Identical duplicate location lines are harmless, but a conflicting aisle/frozen value is rejected.
            if sku in locations and locations[sku] != location:
                rejects.append((index, f"conflicts with an earlier location for {sku}"))
                continue
    
            locations[sku] = location
    
        return locations, rejects
    
    
    def pick_key(sku: str, locations: Dict[str, Location]) -> Tuple[int, int, str]:
        """Build composite sort key (section_rank, numeric_aisle, sku_id).
    
        section_rank: 0 = non-frozen, 1 = frozen (after non-frozen), 2 = missing location (very end).
        """
        location = locations.get(sku)
        if location is None:
            return (2, 0, sku)
        if location.frozen:
            return (1, location.aisle, sku)
        return (0, location.aisle, sku)
    
    
    def aisle_order(order_lines: List[str], location_lines: List[str]) -> List[str]:
        """Part 3: distinct ordered SKUs sorted by numeric aisle, frozen items last, unknowns at end."""
        records, _ = parse_order_lines(order_lines)
        locations, _ = parse_locations(location_lines)
    
        # keyed_skus: list of (section_rank, numeric_aisle, sku_id) tuples for Python tuple sorting.
        keyed_skus: List[Tuple[int, int, str]] = []
        for sku in group_by_sku(records):
            keyed_skus.append(pick_key(sku, locations))
    
        keyed_skus.sort()
    
        ordered_skus: List[str] = []
        for _, _, sku in keyed_skus:
            ordered_skus.append(sku)
        return ordered_skus
    
  7. Trace Examples 1, 2, and 3 end to end

    Let's trace the sample cart across all three stages:

    Order lines:
      0: OAT|Rolled Oats|6|150     -> valid: OrderLine("OAT", "Rolled Oats", 6, 150)
      1: YOG|Greek Yogurt|3|200    -> valid: OrderLine("YOG", "Greek Yogurt", 3, 200)
      2: PEAS|Frozen Peas|1|449    -> valid: OrderLine("PEAS", "Frozen Peas", 1, 449)
      3: ERR1|Bad Qty|two|150      -> rejected: quantity "two" is not digits
      4: ERR2|Missing Price|4      -> rejected: 3 fields instead of 4
      5: OAT|Rolled Oats|1|150     -> valid: OrderLine("OAT", "Rolled Oats", 1, 150)
    
    Stage 1 totals:
      total_quantity = 6 + 3 + 1 + 1 = 11
      total_cents    = 900 + 600 + 449 + 150 = 2099 -> "20.99"
    
    Stage 2 promotions (OAT|axf|20, OAT|bxf|4|2, YOG|axf|15, PEAS|bxf|2|1):
      OAT  (7 @ 150 = 1050): 20% off -> 840 | buy 4 get 2 -> 5 paid = 750 -> wins: (750, "buy 4 get 2 free")
      YOG  (3 @ 200 =  600): 15% off -> 510                               -> wins: (510, "15% off")
      PEAS (1 @ 449 =  449): buy 2 get 1 -> 1 paid = 449 (ties baseline)  -> wins: (449, "")
      discounted total = 750 + 510 + 449 = 1709 -> (11, "17.09")
    
    Stage 3 locations (YOG|12|false, OAT|4|false, PEAS|2|true):
      OAT  -> key (0,  4, "OAT")
      YOG  -> key (0, 12, "YOG")
      PEAS -> key (1,  2, "PEAS")   (frozen section_rank = 1 puts PEAS after all non-frozen items)
      Sorted order -> ["OAT", "YOG", "PEAS"]
    
  8. Complete solution

    from typing import Dict, List, NamedTuple, Optional, Tuple
    import re
    
    # Reject: (0-based line index in input list, plain-English rejection reason), e.g. (3, "empty SKU id").
    Reject = Tuple[int, str]
    
    # Match one or more plain ASCII digits ("0"-"9") with no signs, spaces, or underscores.
    DIGITS = re.compile(r"[0-9]+")
    
    
    class OrderLine(NamedTuple):
        sku: str
        name: str
        quantity: int
        unit_cents: int
    
    
    class Location(NamedTuple):
        aisle: int
        frozen: bool
    
    
    # ---------- Part 1: parse order lines, exact totals ----------
    
    def split_fields(line: str) -> List[str]:
        """Split a pipe-delimited line and trim surrounding spaces from every field."""
        fields = []
        for raw_field in line.split("|"):
            fields.append(raw_field.strip())
        return fields
    
    
    def parse_count(text: str) -> Optional[int]:
        """Parse a whole number >= 0 written with ASCII digits only, or return None.
    
        Python's built-in int() is too lenient on its own because it accepts "+7" and "1_000".
        """
        if DIGITS.fullmatch(text) is None:
            return None
        return int(text)
    
    
    def parse_order_line(line: str) -> Tuple[Optional[OrderLine], str]:
        """Validate one 'SKUid|SKUNAME|QUANTITY|Price' line into (OrderLine, '') or (None, reason)."""
        fields = split_fields(line)
        if len(fields) != 4:
            return None, f"expected 4 fields, got {len(fields)}"
    
        sku, name, quantity_text, price_text = fields
        if sku == "":
            return None, "empty SKU id"
    
        # Quantity must be a whole number >= 1 because ordering 0 items is meaningless.
        quantity = parse_count(quantity_text)
        if quantity is None or quantity == 0:
            return None, "quantity must be a positive whole number"
    
        # Unit price can be 0 (a free item), so any whole number >= 0 is valid.
        unit_cents = parse_count(price_text)
        if unit_cents is None:
            return None, "price must be a whole number of cents"
    
        return OrderLine(sku, name, quantity, unit_cents), ""
    
    
    def parse_order_lines(lines: List[str]) -> Tuple[List[OrderLine], List[Reject]]:
        """Return valid order lines in input order, plus rejected (index, reason) pairs.
    
        A SKU locks in the unit price of its first valid line; any later line for the
        same SKU with a different unit price is rejected so per-SKU pricing is unambiguous.
        """
        valid: List[OrderLine] = []
        rejects: List[Reject] = []
        # price_of_sku: dict mapping sku -> unit_cents from its first valid line, e.g. {"OAT": 150}.
        price_of_sku: Dict[str, int] = {}
    
        for index, line in enumerate(lines):
            record, reason = parse_order_line(line)
            if record is None:
                rejects.append((index, reason))
                continue
    
            known_price = price_of_sku.get(record.sku)
            if known_price is not None and known_price != record.unit_cents:
                rejects.append((index, f"price conflicts with an earlier line for {record.sku}"))
                continue
    
            price_of_sku[record.sku] = record.unit_cents
            valid.append(record)
    
        return valid, rejects
    
    
    def format_dollars(cents: int) -> str:
        """Format non-negative integer cents as 'D.CC', e.g. 2099 -> '20.99', 5 -> '0.05'."""
        dollars = cents // 100
        remaining_cents = cents % 100
        # ':02d' pads single-digit cents with a leading zero so 5 cents formats as "0.05", not "0.5".
        return f"{dollars}.{remaining_cents:02d}"
    
    
    def order_totals(lines: List[str]) -> Tuple[int, str]:
        """Part 1: return (total quantity, total price in dollars) across all valid order lines."""
        records, _ = parse_order_lines(lines)
        total_quantity = 0
        total_cents = 0
        for record in records:
            total_quantity += record.quantity
            total_cents += record.quantity * record.unit_cents
        return total_quantity, format_dollars(total_cents)
    
    
    # ---------- Part 2: promotions, cheapest option per SKU ----------
    
    class PercentOff:
        """Promotion 'SKU|axf|P': P% off the SKU's combined line amount."""
    
        def __init__(self, percent: int):
            self.percent = percent
    
        def price_cents(self, quantity: int, unit_cents: int) -> int:
            full_cents = quantity * unit_cents
            # Adding 50 before integer division by 100 rounds >= 0.5 cents up in the customer's favor.
            discount_cents = (full_cents * self.percent + 50) // 100
            return full_cents - discount_cents
    
        def label(self) -> str:
            return f"{self.percent}% off"
    
    
    class BuyXGetYFree:
        """Promotion 'SKU|bxf|X|Y': in every group of X + Y units, Y units are free."""
    
        def __init__(self, buy: int, free: int):
            self.buy = buy
            self.free = free
    
        def price_cents(self, quantity: int, unit_cents: int) -> int:
            group_size = self.buy + self.free
            full_groups = quantity // group_size
            leftover_units = quantity % group_size
            # In an incomplete group, the customer pays for at most X units and any extras beyond X are free.
            paid_in_leftover = min(leftover_units, self.buy)
            paid_units = full_groups * self.buy + paid_in_leftover
            return paid_units * unit_cents
    
        def label(self) -> str:
            return f"buy {self.buy} get {self.free} free"
    
    
    def parse_percent_off(values: List[str]) -> Tuple[Optional[PercentOff], str]:
        if len(values) != 1:
            return None, "axf takes one value"
        percent = parse_count(values[0])
        if percent is None or percent > 100:
            return None, "percent must be a whole number from 0 to 100"
        return PercentOff(percent), ""
    
    
    def parse_buy_x_get_y(values: List[str]) -> Tuple[Optional[BuyXGetYFree], str]:
        if len(values) != 2:
            return None, "bxf takes two values"
        buy = parse_count(values[0])
        free = parse_count(values[1])
        if buy is None or free is None or buy == 0 or free == 0:
            return None, "buy and free counts must be positive whole numbers"
        return BuyXGetYFree(buy, free), ""
    
    
    # PROMOTION_PARSERS: registry mapping promo type code -> parser function; new deals plug in here.
    PROMOTION_PARSERS = {
        "axf": parse_percent_off,
        "bxf": parse_buy_x_get_y,
    }
    
    
    def parse_promotions(lines: List[str]) -> Tuple[Dict[str, list], List[Reject]]:
        """Group valid promotion objects by SKU in input order, plus rejected (index, reason) pairs."""
        # by_sku: dict mapping sku -> list of promotion objects (PercentOff / BuyXGetYFree) in input order.
        by_sku: Dict[str, list] = {}
        rejects: List[Reject] = []
    
        for index, line in enumerate(lines):
            fields = split_fields(line)
            if len(fields) < 2 or fields[0] == "":
                rejects.append((index, "expected SKUid|type|values"))
                continue
    
            sku = fields[0]
            promo_type = fields[1]
            parser = PROMOTION_PARSERS.get(promo_type)
            if parser is None:
                rejects.append((index, f"unknown promotion type {promo_type!r}"))
                continue
    
            promotion, reason = parser(fields[2:])
            if promotion is None:
                rejects.append((index, reason))
                continue
    
            if sku not in by_sku:
                by_sku[sku] = []
            by_sku[sku].append(promotion)
    
        return by_sku, rejects
    
    
    def group_by_sku(records: List[OrderLine]) -> Dict[str, Tuple[int, int]]:
        """Combine multiple lines for the same SKU into {sku: (combined_quantity, unit_cents)}."""
        # groups: dict mapping sku -> (combined_quantity, unit_cents) in first-appearance order.
        groups: Dict[str, Tuple[int, int]] = {}
        for record in records:
            if record.sku not in groups:
                groups[record.sku] = (record.quantity, record.unit_cents)
            else:
                old_quantity, unit_cents = groups[record.sku]
                groups[record.sku] = (old_quantity + record.quantity, unit_cents)
        return groups
    
    
    def best_price(quantity: int, unit_cents: int, promotions: list) -> Tuple[int, str]:
        """Return (lowest_cents, winning_label) for one SKU; 'no promotion' wins ties."""
        best_cents = quantity * unit_cents
        best_label = ""
        for promotion in promotions:
            candidate_cents = promotion.price_cents(quantity, unit_cents)
            # Strict '<' ensures no-promotion wins ties at full price and earlier promos win equal deals.
            if candidate_cents < best_cents:
                best_cents = candidate_cents
                best_label = promotion.label()
        return best_cents, best_label
    
    
    def best_prices(order_lines: List[str], promo_lines: List[str]) -> Dict[str, Tuple[int, str]]:
        """Part 2: return {sku: (cents_after_best_promotion, label_or_empty)}."""
        records, _ = parse_order_lines(order_lines)
        promotions_by_sku, _ = parse_promotions(promo_lines)
        result: Dict[str, Tuple[int, str]] = {}
        for sku, (quantity, unit_cents) in group_by_sku(records).items():
            sku_promotions = promotions_by_sku.get(sku, [])
            result[sku] = best_price(quantity, unit_cents, sku_promotions)
        return result
    
    
    def totals_after_promotions(order_lines: List[str], promo_lines: List[str]) -> Tuple[int, str]:
        """Part 2: return (total quantity, total price in dollars after best promotion per SKU)."""
        records, _ = parse_order_lines(order_lines)
        promotions_by_sku, _ = parse_promotions(promo_lines)
        sku_groups = group_by_sku(records)
    
        total_quantity = 0
        total_cents = 0
        for sku, (quantity, unit_cents) in sku_groups.items():
            # Every physical unit in the cart counts toward total_quantity, even if a promotion makes it free.
            total_quantity += quantity
            sku_promotions = promotions_by_sku.get(sku, [])
            discounted_cents, _ = best_price(quantity, unit_cents, sku_promotions)
            total_cents += discounted_cents
    
        return total_quantity, format_dollars(total_cents)
    
    
    # ---------- Part 3: aisle ordering, frozen last ----------
    
    def parse_location_line(line: str) -> Tuple[Optional[Tuple[str, Location]], str]:
        """Validate one 'SKUid|aisle|isFrozen' line into ((sku, Location), '') or (None, reason)."""
        fields = split_fields(line)
        if len(fields) != 3:
            return None, f"expected 3 fields, got {len(fields)}"
    
        sku, aisle_text, frozen_text = fields
        if sku == "":
            return None, "empty SKU id"
    
        aisle = parse_count(aisle_text)
        if aisle is None:
            return None, "aisle must be a whole number"
    
        frozen_lower = frozen_text.lower()
        if frozen_lower not in ("true", "false"):
            return None, "isFrozen must be true or false"
    
        return (sku, Location(aisle, frozen_lower == "true")), ""
    
    
    def parse_locations(lines: List[str]) -> Tuple[Dict[str, Location], List[Reject]]:
        """Map each SKU to its first valid Location; reject conflicting later locations."""
        # locations: dict mapping sku -> Location(aisle, frozen), e.g. {"OAT": Location(4, False)}.
        locations: Dict[str, Location] = {}
        rejects: List[Reject] = []
    
        for index, line in enumerate(lines):
            parsed, reason = parse_location_line(line)
            if parsed is None:
                rejects.append((index, reason))
                continue
    
            sku, location = parsed
            # Identical duplicate location lines are harmless, but a conflicting aisle/frozen value is rejected.
            if sku in locations and locations[sku] != location:
                rejects.append((index, f"conflicts with an earlier location for {sku}"))
                continue
    
            locations[sku] = location
    
        return locations, rejects
    
    
    def pick_key(sku: str, locations: Dict[str, Location]) -> Tuple[int, int, str]:
        """Build composite sort key (section_rank, numeric_aisle, sku_id).
    
        section_rank: 0 = non-frozen, 1 = frozen (after non-frozen), 2 = missing location (very end).
        """
        location = locations.get(sku)
        if location is None:
            return (2, 0, sku)
        if location.frozen:
            return (1, location.aisle, sku)
        return (0, location.aisle, sku)
    
    
    def aisle_order(order_lines: List[str], location_lines: List[str]) -> List[str]:
        """Part 3: distinct ordered SKUs sorted by numeric aisle, frozen items last, unknowns at end."""
        records, _ = parse_order_lines(order_lines)
        locations, _ = parse_locations(location_lines)
    
        # keyed_skus: list of (section_rank, numeric_aisle, sku_id) tuples for Python tuple sorting.
        keyed_skus: List[Tuple[int, int, str]] = []
        for sku in group_by_sku(records):
            keyed_skus.append(pick_key(sku, locations))
    
        keyed_skus.sort()
    
        ordered_skus: List[str] = []
        for _, _, sku in keyed_skus:
            ordered_skus.append(sku)
        return ordered_skus
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this cart processor as an assembly line with a strict bouncer at the door, a penny-only cash register, and a three-level sorting tag for the store picker. Every raw text line is validated at the boundary into a clean named tuple (a lightweight, read-only object with named fields), all money stays in whole integer cents until final formatting, every promotion computes an exact cent price so the lowest bill wins, and store picking sorts products once using a composite sort key (a multi-field tuple compared left to right).

A quick-and-dirty implementation hits three classic traps right away. First, storing dollars in binary floating-point numbers (float) produces rounding drift like 0.10 + 0.20 == 0.30000000000000004. Second, comparing deals by their labels ("20% off" vs. "buy 4 get 2 free") fails because the cheaper offer shifts with the shopper's quantity. Third, sorting aisle strings alphabetically puts "12" ahead of "4" instead of walking the store in numeric aisle order.

Here is how our sample cart moves through all three stages:

  1. Stage 1 (Totals): OAT|Rolled Oats|6|150, YOG|Greek Yogurt|3|200, PEAS|Frozen Peas|1|449, and OAT|Rolled Oats|1|150 validate cleanly while malformed lines are skipped with reasons, giving 6 + 3 + 1 + 1 = 11 items and 900 + 600 + 449 + 150 = 2099 cents ("20.99").
  2. Stage 2 (Promotions): on 7 combined "OAT" units (1050 cents), "20% off" costs 840 cents while "buy 4 get 2 free" charges for 5 units (750 cents), so 750 wins; "YOG" drops to 510 cents ("15% off"); "PEAS" has 1 unit so "buy 2 get 1 free" saves nothing (449 cents, ""), giving "17.09".
  3. Stage 3 (Aisle order): "OAT" (aisle 4, non-frozen) gets key (0, 4, "OAT"), "YOG" (aisle 12, non-frozen) gets (0, 12, "YOG"), and frozen "PEAS" (aisle 2, frozen) gets (1, 2, "PEAS"), sorting in one pass to ["OAT", "YOG", "PEAS"].

Complexity

  • Stage 1 — Time O(C), Space O(n): we scan all C characters of the order input once, splitting each line on "|" and checking a price_of_sku dictionary in O(1) time per line. Storing the n valid OrderLine records and up to n SKU prices uses O(n) memory.
  • Stage 2 — Time O(C + P), Space O(s + p): after scanning C order characters and P promotion characters once, grouping the n valid order lines by SKU takes one O(n) dictionary pass, and evaluating each of the p valid promotions takes O(1) integer math. Keeping the s distinct SKUs and p promotion objects takes O(s + p) space.
  • Stage 3 — Time O(C + L + s log s), Space O(s + k): scanning L location characters builds a dictionary of k valid locations in linear time, and sorting the s distinct ordered SKUs performs O(s log s) tuple comparisons. Holding the location map and keyed SKU list uses O(s + k) memory.

Edge cases

  • Empty input: returns (0, "0.00") for totals, {} for best prices, and [] for aisle ordering.
  • Zero-cent unit prices vs. zero quantities: a unit price of 0 cents is valid (a complimentary item), whereas a quantity of 0 is rejected because an order line must purchase at least 1 unit.
  • Split lines for the same SKU: quantities across multiple valid lines for "OAT" sum together before promotions run; any later line for "OAT" carrying a different unit price is rejected.
  • Incomplete buy-X-get-Y groups: under buy 4 get 2 free, 5 units still pay for 4 (min(5, 4) = 4) and 7 units pay for 5 (4 + min(1, 4) = 5). Quantities of X or fewer save 0 cents, so "no promotion" keeps the tie.
  • Percentage boundaries and half-cent ties: 0% ties full price so "no promotion" wins, 100% reduces the price to 0 cents, and an exact half-cent discount (1 unit at 5 cents with 10% off = 0.5 cents) rounds up to 1 cent off (4 cents paid).
  • Missing or conflicting store locations: frozen items always sort after non-frozen items even when their aisle number is smaller (aisle 2 frozen comes after aisle 12 non-frozen), and SKUs with no valid location record go at the very end (section_rank = 2).

Common mistakes

  • Using float for money arithmetic: 0.1 + 0.2 produces 0.30000000000000004, and str(50 / 100) formats "0.5" instead of "0.50". Always compute in integer cents and format once with f"{cents // 100}.{cents % 100:02d}".
  • Relying on bare int() for input validation: int("+7"), int(" 7"), and int("1_000") all succeed in Python; matching [0-9]+ with a regular expression (a character-by-character pattern check) rejects signs and underscores cleanly.
  • Rounding percentages with Python's round() or per unit: round() uses round-half-to-even (round(0.5) == 0), whereas (full_cents * percent + 50) // 100 rounds exact half cents in the customer's favor once on the SKU's combined amount.
  • Applying promotions per order line instead of per SKU: evaluating lines separately prevents 6 units + 1 unit of "OAT" from combining into 7 units for "buy 4 get 2 free".
  • Sorting aisles as strings or omitting a tie-breaker: string order puts "12" before "4", and omitting sku from the sort tuple leaves same-aisle ties dependent on input order.

Follow-up questions

  • What would need to change if a single SKU could combine multiple deals at once, such as applying a percentage markdown after free bundle units? First lock down the exact business rule, because subtracting both discounts from full price differs from removing free bundle units first and applying the percentage to the remaining paid subtotal (and integer rounding can shift by a cent depending on order). Once agreed — typically bundle freebies first, then percentage off rounded once — tag deals as exclusive or stackable, evaluate candidate stacked pairs (buy_x_get_y, percent_off) via paid = buy_get.price_cents(...) followed by (paid * pct + 50) // 100, and let best_price pick the lowest candidate as usual.
  • How would you extend the pricing engine to support cross-SKU mix-and-match offers, like picking any three eligible items for a flat bundle price? Per-SKU pricing is no longer independent once assigning an item to a cross-SKU bundle prevents it from counting toward its own SKU's deal. Register the group offer in PROMOTION_PARSERS (for example, GROUP|nfor|3|900|OAT,YOG,PEAS) and use dynamic programming (solving a decision problem by caching optimal answers to smaller subproblems, here indexed by which SKU we are deciding and how many bundle slots remain) to partition each SKU's quantity between cross-SKU bundles and its single-SKU best_price.
  • How would you adapt your implementation to handle multi-million-line order feeds in bounded memory as a stream? Accept any line iterator (for index, line in enumerate(stream)) instead of a materialized List[str], fold valid quantities directly into the {sku: (combined_quantity, unit_cents)} dictionary so RAM stays O(distinct SKUs) instead of O(lines), and emit rejected lines straight to an error sink or counter map rather than accumulating a full rejects list in memory. If even distinct SKUs exceed RAM, hash-partition incoming lines by sku onto temporary disk shards and price each shard independently.
  • What structured error reporting would you return so upstream data producers can diagnose and fix malformed records? Replace bare (index, reason) pairs with a structured diagnostic record carrying the feed name ("orders", "promotions", "locations"), 1-based line number, machine-readable error code (such as INVALID_QUANTITY or UNIT_PRICE_CONFLICT), offending field name, plain-English detail, and a truncated raw line sample. Return per-code summary counts (plus the first conflicting line number for price/location clashes) and fail the batch loudly if the rejection rate exceeds a configured safety threshold.

Follow-up questions

Similar questions

More Instacart interview questions

All 87 Instacart questions →