Evolve a Checkout Cart for Grouped, Discounted, Sorted Receipts

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

You are refactoring a checkout module that converts scanned item names into formatted receipts across four progressive milestones. Prices are stored and summed in exact integer cents rather than floating-point numbers, and item names are matched case-insensitively with surrounding whitespace ignored.

Implement the following helpers and classes:

  1. Currency & name helpers

    • to_cents(text: str) -> int: Strip outer whitespace and parse a non-negative decimal price string with at most two fractional digits into integer cents (for example, "3.00" -> 300, " 2.25 " -> 225, "5" -> 500). Raise ValueError for non-numeric text, NaN or Infinity, negative values (including "-0.00"), or sub-cent precision such as "3.125".
    • format_cents(cents: int) -> str: Format non-negative integer cents as "<dollars>.<cents>" with two zero-padded decimal digits (915 -> "9.15", 5 -> "0.05"). Raise ValueError if cents < 0.
    • normalize(name: str) -> str: Trim surrounding whitespace and convert to lowercase (" Pear " -> "pear").
  2. Milestone 1 — Scan-order itemized receipt

    • itemized_receipt(stream: List[str], prices: Dict[str, int]) -> List[str]: Given a sequence of raw item strings and a catalog mapping item names to unit prices in cents, skip blank entries and items missing from prices. Emit "<normalized_name> <unit_price>" for each valid scan in arrival order, ending with "Total <total_price>".
  3. Milestones 2–4 — Grouped cart, cycle promotions, and alphabetical receipts

    • BuyGetFree(item: str, buy: int = 3, free: int = 2): Represents a repeating "buy buy, get free free" promotion on one normalized item (raise ValueError if buy < 1 or free < 0).
      • charged_units(quantity: int) -> int: Raise ValueError if quantity < 0. Partition quantity into repeating cycles of buy + free scanned units: within each cycle, the first buy units are paid and the remaining free units are free (so for buy=3, free=2, scanned units 1..3 are paid, 4..5 are free, 6..8 are paid, 9..10 are free, and a partial trailing group of r units charges min(r, buy)).
    • ShoppingCart(prices: Dict[str, int], promotions: Optional[List[BuyGetFree]] = None):
      • Normalize catalog keys and register at most one BuyGetFree promotion per normalized item (raise ValueError on duplicate promotions for the same item).
      • add_item(name: str) -> bool: Add one unit if normalize(name) is non-empty and exists in the catalog (True); otherwise leave the cart unchanged (False).
      • remove_item(name: str) -> bool: Remove one unit if at least one is currently in the cart (True, omitting the item from receipts once its count reaches 0); otherwise leave the cart unchanged (False).
      • scan(stream: List[str]) -> List[str]: Call add_item on every element of stream in order and return the rejected raw strings in order.
      • quantity(name: str) -> int: Return the current unit count of name in the cart (0 if absent).
      • total_cents() -> int: Return total payable cents across all items currently in the cart after applying promotions.
      • receipt_lines() -> List[str]: Return one grouped line per item with quantity >= 1, sorted in ascending alphabetical order of normalized item name: text <name>, <quantity>, <unit_price> x<charged_units> followed by "Total <total_price>".
      • print_receipt() -> None: Print each string in receipt_lines() on its own line to standard output.

Examples

Example 1

Input:
  prices = {"coffee": 300, "muffin": 225, "pear": 90}
  stream = ["coffee", "muffin", "", "juice", " Pear ", "COFFEE"]
  itemized_receipt(stream, prices)

Output:
  [
      "coffee 3.00",
      "muffin 2.25",
      "pear 0.90",
      "coffee 3.00",
      "Total 9.15",
  ]

Explanation: Blank "" and unlisted "juice" are skipped. " Pear " and "COFFEE" normalize to "pear" (0.90) and "coffee" (3.00), preserving scan order and summing to 300 + 225 + 90 + 300 = 915 cents ("9.15").

Example 2

Input:
  prices = {"coffee": 300, "muffin": 225, "pear": 90}
  cart = ShoppingCart(prices, [BuyGetFree("coffee", buy=3, free=2)])
  rejected = cart.scan(["muffin", "coffee", "pear", "juice", "coffee", "coffee", "coffee", "coffee"])
  before_removals = cart.receipt_lines()

  cart.remove_item("coffee")
  cart.remove_item("coffee")
  cart.remove_item("coffee")
  cart.remove_item("pear")
  after_removals = cart.receipt_lines()

Output:
  rejected = ["juice"]
  before_removals = [
      "coffee, 5, 3.00 x3",
      "muffin, 1, 2.25 x1",
      "pear, 1, 0.90 x1",
      "Total 12.15",
  ]
  after_removals = [
      "coffee, 2, 3.00 x2",
      "muffin, 1, 2.25 x1",
      "Total 8.25",
  ]

Explanation: Scanning 5 coffees triggers one full 3 + 2 cycle, charging for 3 units (3 * 300 = 900 cents), plus 1 muffin (225) and 1 pear (90) in alphabetical order for 1215 cents ("12.15"). Removing 3 coffees drops the coffee count to 2 (charging for 2 units = 600 cents), and removing the sole pear drops "pear" from the receipt completely, leaving 600 + 225 = 825 cents ("8.25").

Constraints

  • 0 <= len(prices) <= 10^4, with non-negative integer cent prices 0 <= unit_cents <= 10^9.
  • 0 <= len(stream) <= 10^5 across itemized_receipt and scan calls.
  • buy >= 1 and free >= 0 for valid BuyGetFree rules (invalid parameters raise ValueError).
  • At most one BuyGetFree promotion may target any normalized item name.

Step-by-step walkthrough

  1. Clarify requirements and design choices

    In a progressive object-oriented refactoring exercise, requirements build across four milestones, so start by locking down the exact invariants that govern your data model:

    • Input stream and catalog: Each stream element is a raw item-name string ("coffee", " Pear ", ""). Unit prices live in a catalog mapping item names to integer cents ({"coffee": 300, "muffin": 225, "pear": 90}).
    • Name normalization: Item names match case-insensitively and ignore surrounding whitespace (" Pear " -> "pear").
    • Invalid entries and missing removals: Blank strings or unknown items ("juice") never crash checkout — add_item returns False and leaves the basket untouched, while scan collects rejected entries in arrival order. Removing an absent item also returns False.
    • "Buy three, get two free" semantics: Evaluated unit by unit in repeating cycles of 5: units 1–3 are paid, units 4–5 are free, units 6–8 are paid, units 9–10 are free. Thus 4 coffees charge for 3, and 6 coffees charge for 4.
    • Milestone 1 vs Milestones 2–4: Milestone 1's scan-order receipt lives in itemized_receipt(stream, prices), while ShoppingCart stores per-item counts and emits grouped, promoted, alphabetically sorted lines.
    Helpers & Milestone 1:
      to_cents("3.00") -> 300          format_cents(915) -> "9.15"
      normalize(" Pear ") -> "pear"
      itemized_receipt(stream, prices) -> ["coffee 3.00", ..., "Total 9.15"]
    
    Milestones 2 - 4:
      BuyGetFree(item="coffee", buy=3, free=2).charged_units(quantity) -> paid units
      ShoppingCart(prices, promotions)
        .add_item(name) / .remove_item(name) / .scan(stream) / .quantity(name)
        .total_cents()  / .receipt_lines()   / .print_receipt()
    
  2. Part 1: Exact money in integer cents and the itemized receipt

    Standard binary floating-point numbers (float) cannot represent most base-10 fractions like 0.10 exactly: in Python, 0.1 + 0.2 evaluates to 0.30000000000000004, and adding 0.10 ten times gives 0.9999999999999999. To guarantee exact arithmetic across thousands of scans, we convert money to integer cents on input and format back to "dollars.cents" only at display time:

    • to_cents(text) parses text with Decimal (which represents base-10 decimals exactly), rejects NaN, Infinity, negative values (including "-0.00" via amount.is_signed()), and sub-cent strings like "3.125" where amount * 100 is not an exact integer.
    • format_cents(cents) splits non-negative cents using integer division (cents // 100) and remainder (cents % 100), zero-padding cents to two digits (:02d) so 5 cents formats as "0.05".
    • normalize(name) centralizes .strip().lower() in one function so catalog keys, scanned names, removals, and promotions always agree.
    from typing import Dict, List, Optional
    from decimal import Decimal, InvalidOperation
    
    
    def to_cents(text: str) -> int:
        """Parse a price string such as '3.00' into exact integer cents (300)."""
        # Parse via Decimal instead of float so "0.10" or "3.00" never suffers binary float drift.
        try:
            amount = Decimal(text.strip())
        except InvalidOperation:
            raise ValueError(f"not a price: {text!r}")
    
        # Reject NaN, Infinity, negative numbers, and "-0.00" (is_signed() catches negative zero).
        if not amount.is_finite() or amount.is_signed():
            raise ValueError(f"not a price: {text!r}")
    
        cents = amount * 100
        # Reject sub-cent fractions like "3.125" where cents (312.5) is not a whole integer.
        if cents != cents.to_integral_value():
            raise ValueError(f"more than two decimal places: {text!r}")
        return int(cents)
    
    
    def format_cents(cents: int) -> str:
        """Format non-negative integer cents: 1215 -> '12.15', 5 -> '0.05'."""
        if cents < 0:
            raise ValueError(f"cents must be non-negative: {cents}")
        dollars = cents // 100
        rem_cents = cents % 100
        # :02d zero-pads single-digit cents so 5 cents formats as "0.05", not "0.5".
        return f"{dollars}.{rem_cents:02d}"
    
    
    def normalize(name: str) -> str:
        """Normalize an item name by trimming whitespace and lowercasing."""
        return name.strip().lower()
    
    
    def itemized_receipt(stream: List[str], prices: Dict[str, int]) -> List[str]:
        """Part 1: return one 'name price' line per valid scanned unit, then 'Total X'."""
        # Normalize catalog keys once so lookups match regardless of input casing.
        catalog: Dict[str, int] = {}
        for item_name, unit_cents in prices.items():
            catalog[normalize(item_name)] = unit_cents
    
        lines: List[str] = []
        total_cents = 0
        for entry in stream:
            name = normalize(entry)
            # Skip blank strings and unknown catalog items without aborting the checkout.
            if name == "" or name not in catalog:
                continue
            unit_cents = catalog[name]
            lines.append(f"{name} {format_cents(unit_cents)}")
            total_cents += unit_cents
    
        lines.append(f"Total {format_cents(total_cents)}")
        return lines
    
  3. Part 2: Refactor cart storage from a list of units to a count dictionary

    A naive checkout class appends every scanned item to a flat list. Once receipts group items by type (coffee, 3, 3.00 x3), scan order no longer appears on the receipt — only counts per item type matter. Replacing the flat list (n scanned units) with a dictionary counts: Dict[str, int] (k distinct item types, where k <= n) turns linear scans into constant-time dictionary operations:

    Old storage (flat list, n = 5):   ["coffee", "muffin", "coffee", "pear", "coffee"]
                                       -> remove_item("pear") scans & shifts the list: O(n)
    
    New storage (count dict, k = 3):  {"coffee": 3, "muffin": 1, "pear": 1}
                                       -> add_item, remove_item, quantity: O(1) average!
    

    We maintain one critical invariant (a rule guaranteed to hold after every method call): every key in self.counts has a count >= 1. When remove_item drops an item's count from 1 down to 0, we delete the key (del self.counts[key]) so the receipt never prints a "pear, 0, 0.90 x0" ghost line.

    class ShoppingCart:
        """Shopping cart storing per-item counts and applying promotions at receipt time."""
    
        def __init__(self, prices: Dict[str, int], promotions: Optional[List[BuyGetFree]] = None) -> None:
            # self.prices: {"coffee": 300, "muffin": 225, "pear": 90} (normalized name -> unit cents)
            self.prices: Dict[str, int] = {}
            for name, cents in prices.items():
                self.prices[normalize(name)] = cents
    
            # self.promotions: {"coffee": BuyGetFree("coffee", 3, 2)} (at most one promo per item)
            self.promotions: Dict[str, BuyGetFree] = {}
            for promo in promotions or []:
                if promo.item in self.promotions:
                    raise ValueError(f"more than one promotion for {promo.item!r}")
                self.promotions[promo.item] = promo
    
            # self.counts: {"coffee": 3, "muffin": 1} (invariant: only keys with count >= 1 exist)
            self.counts: Dict[str, int] = {}
    
        def add_item(self, name: str) -> bool:
            """Add one unit of `name`; return False if blank or missing from the catalog."""
            key = normalize(name)
            if key == "" or key not in self.prices:
                return False
            self.counts[key] = self.counts.get(key, 0) + 1
            return True
    
        def remove_item(self, name: str) -> bool:
            """Remove one unit of `name`; return False if none are currently in the cart."""
            key = normalize(name)
            current_count = self.counts.get(key, 0)
            if current_count == 0:
                return False
            if current_count == 1:
                # Delete the key when count reaches 0 so receipt_lines() never prints a 0-quantity row.
                del self.counts[key]
            else:
                self.counts[key] = current_count - 1
            return True
    
        def scan(self, stream: List[str]) -> List[str]:
            """Scan a list of entries, returning rejected entries in their original form."""
            rejected: List[str] = []
            for entry in stream:
                if not self.add_item(entry):
                    rejected.append(entry)
            return rejected
    
        def quantity(self, name: str) -> int:
            """Return how many units of `name` are currently in the cart."""
            return self.counts.get(normalize(name), 0)
    
  4. Part 3: Model "buy three, get two free" as a pure calculation

    Where should promotional logic execute — when items are added, or when the receipt is computed? - Trap (mutating counts or totals during add_item): If scanning 3 coffees automatically inserts 2 "free" coffees or subtracts from a running total, what happens when the shopper puts 1 coffee back? Guessing whether a paid unit or a free unit left the basket easily leaves stale discounts behind. - Clean design (stateless calculation at receipt time): Keep self.counts strictly equal to physical units in the basket, and give BuyGetFree a pure method charged_units(quantity) that computes payable units from the current count. Removals then work automatically with zero undo logic!

    With buy = 3 and free = 2, items form repeating blocks of group_size = 3 + 2 = 5:

    Scanned unit #:   1     2     3     4     5   |   6     7     8     9    10   |  11
    Status:          PAID  PAID  PAID  FREE  FREE |  PAID  PAID  PAID  FREE  FREE | PAID
                     \_________ group 1 _________/ \_________ group 2 _________/   \_rem_/
    
    Formula:
      full_groups       = quantity // (buy + free)
      remainder         = quantity %  (buy + free)
      paid_in_remainder = min(remainder, buy)
      charged_units     = full_groups * buy + paid_in_remainder
    
    Check:
      quantity = 4 -> 0 * 3 + min(4, 3) = 3 paid   (4th unit is free)
      quantity = 5 -> 1 * 3 + min(0, 3) = 3 paid   (4th & 5th units are free)
      quantity = 6 -> 1 * 3 + min(1, 3) = 4 paid   (new cycle starts on unit 6)
    
    class BuyGetFree:
        """'Buy `buy`, get `free` free' promotion for one item, repeating in cycles."""
    
        def __init__(self, item: str, buy: int = 3, free: int = 2) -> None:
            if buy < 1 or free < 0:
                raise ValueError("need buy >= 1 and free >= 0")
            self.item = normalize(item)
            self.buy = buy
            self.free = free
    
        def charged_units(self, quantity: int) -> int:
            """Return how many of `quantity` scanned units the customer pays for."""
            if quantity < 0:
                raise ValueError(f"quantity must be non-negative: {quantity}")
            # Every cycle of (buy + free) units charges for `buy` units and gives `free` units free.
            group_size = self.buy + self.free
            full_groups = quantity // group_size
            remainder = quantity % group_size
            # In an incomplete trailing cycle, the first `buy` units are paid and any extra are free.
            paid_in_remainder = min(remainder, self.buy)
            return full_groups * self.buy + paid_in_remainder
    
  5. Part 4: Sort receipt lines alphabetically on demand

    Should the cart maintain sorted item names during every add_item and remove_item, or sort only when receipt_lines() runs? - Maintaining a separate sorted list alongside the dict costs O(k) shifting on every new item type and every final-unit removal. - Sorting self.counts keys on demand (sorted(self.counts)) costs O(k log k) once at checkout, keeping every scan and removal O(1) average time. Because normalize already lowercased every key, "Coffee", " coffee ", and "COFFEE" merged into "coffee", so alphabetical order is clean and tie-free.

    Separating formatting (receipt_lines returning List[str]) from console output (print_receipt) also makes unit tests clean and fast.

    # Methods inside class ShoppingCart:
    def _charged_units(self, name: str) -> int:
        """Compute paid units dynamically from current count so removals never leave stale discounts."""
        quantity = self.counts[name]
        promo = self.promotions.get(name)
        if promo is None:
            return quantity
        return promo.charged_units(quantity)
    
    
    def total_cents(self) -> int:
        """Return the total amount due in cents across all items after promotions."""
        total = 0
        for name in self.counts:
            total += self.prices[name] * self._charged_units(name)
        return total
    
    
    def receipt_lines(self) -> List[str]:
        """Return grouped, promoted, alphabetically sorted receipt lines plus the Total line."""
        lines: List[str] = []
        # Sort item keys on demand (O(k log k) once at checkout) rather than on every scan.
        for name in sorted(self.counts):
            scanned_qty = self.counts[name]
            charged_qty = self._charged_units(name)
            unit_price_str = format_cents(self.prices[name])
            lines.append(f"{name}, {scanned_qty}, {unit_price_str} x{charged_qty}")
        lines.append(f"Total {format_cents(self.total_cents())}")
        return lines
    
    
    def print_receipt(self) -> None:
        """Print every line of receipt_lines() to standard output."""
        for line in self.receipt_lines():
            print(line)
    
  6. Trace Example 2 with promotions and removals

    Let's trace ShoppingCart({"coffee": 300, "muffin": 225, "pear": 90}, [BuyGetFree("coffee", 3, 2)]) across Example 2:

    1. Scan ["muffin", "coffee", "pear", "juice", "coffee", "coffee", "coffee", "coffee"]:
       rejected = ["juice"]
       counts   = {"muffin": 1, "coffee": 5, "pear": 1}
    
       sorted(counts) -> ["coffee", "muffin", "pear"]:
         coffee: qty 5, charged (5//5)*3 + min(0,3) = 3 -> "coffee, 5, 3.00 x3" (900 cents)
         muffin: qty 1, charged 1                       -> "muffin, 1, 2.25 x1" (225 cents)
         pear:   qty 1, charged 1                       -> "pear, 1, 0.90 x1"   ( 90 cents)
         Total:  900 + 225 + 90 = 1215 cents            -> "Total 12.15"
    
    2. Remove 3 coffees and 1 pear:
       counts drops "pear" key completely -> {"muffin": 1, "coffee": 2}
       coffee: qty 2, charged (2//5)*3 + min(2,3) = 2 -> "coffee, 2, 3.00 x2" (600 cents)
       muffin: qty 1, charged 1                       -> "muffin, 1, 2.25 x1" (225 cents)
       Total recomputed cleanly: 600 + 225 = 825 cents -> "Total 8.25"
    
  7. Complete solution

    from typing import Dict, List, Optional
    from decimal import Decimal, InvalidOperation
    
    
    def to_cents(text: str) -> int:
        """Parse a price string such as '3.00' into exact integer cents (300)."""
        # Parse via Decimal instead of float so "0.10" or "3.00" never suffers binary float drift.
        try:
            amount = Decimal(text.strip())
        except InvalidOperation:
            raise ValueError(f"not a price: {text!r}")
    
        # Reject NaN, Infinity, negative numbers, and "-0.00" (is_signed() catches negative zero).
        if not amount.is_finite() or amount.is_signed():
            raise ValueError(f"not a price: {text!r}")
    
        cents = amount * 100
        # Reject sub-cent fractions like "3.125" where cents (312.5) is not a whole integer.
        if cents != cents.to_integral_value():
            raise ValueError(f"more than two decimal places: {text!r}")
        return int(cents)
    
    
    def format_cents(cents: int) -> str:
        """Format non-negative integer cents: 1215 -> '12.15', 5 -> '0.05'."""
        if cents < 0:
            raise ValueError(f"cents must be non-negative: {cents}")
        dollars = cents // 100
        rem_cents = cents % 100
        # :02d zero-pads single-digit cents so 5 cents formats as "0.05", not "0.5".
        return f"{dollars}.{rem_cents:02d}"
    
    
    def normalize(name: str) -> str:
        """Normalize an item name by trimming whitespace and lowercasing."""
        return name.strip().lower()
    
    
    def itemized_receipt(stream: List[str], prices: Dict[str, int]) -> List[str]:
        """Part 1: return one 'name price' line per valid scanned unit, then 'Total X'."""
        # Normalize catalog keys once so lookups match regardless of input casing.
        catalog: Dict[str, int] = {}
        for item_name, unit_cents in prices.items():
            catalog[normalize(item_name)] = unit_cents
    
        lines: List[str] = []
        total_cents = 0
        for entry in stream:
            name = normalize(entry)
            # Skip blank strings and unknown catalog items without aborting the checkout.
            if name == "" or name not in catalog:
                continue
            unit_cents = catalog[name]
            lines.append(f"{name} {format_cents(unit_cents)}")
            total_cents += unit_cents
    
        lines.append(f"Total {format_cents(total_cents)}")
        return lines
    
    
    class BuyGetFree:
        """'Buy `buy`, get `free` free' promotion for one item, repeating in cycles."""
    
        def __init__(self, item: str, buy: int = 3, free: int = 2) -> None:
            if buy < 1 or free < 0:
                raise ValueError("need buy >= 1 and free >= 0")
            self.item = normalize(item)
            self.buy = buy
            self.free = free
    
        def charged_units(self, quantity: int) -> int:
            """Return how many of `quantity` scanned units the customer pays for."""
            if quantity < 0:
                raise ValueError(f"quantity must be non-negative: {quantity}")
            # Every cycle of (buy + free) units charges for `buy` units and gives `free` units free.
            group_size = self.buy + self.free
            full_groups = quantity // group_size
            remainder = quantity % group_size
            # In an incomplete trailing cycle, the first `buy` units are paid and any extra are free.
            paid_in_remainder = min(remainder, self.buy)
            return full_groups * self.buy + paid_in_remainder
    
    
    class ShoppingCart:
        """Shopping cart storing per-item counts and applying promotions at receipt time."""
    
        def __init__(self, prices: Dict[str, int], promotions: Optional[List[BuyGetFree]] = None) -> None:
            # self.prices: {"coffee": 300, "muffin": 225, "pear": 90} (normalized name -> unit cents)
            self.prices: Dict[str, int] = {}
            for name, cents in prices.items():
                self.prices[normalize(name)] = cents
    
            # self.promotions: {"coffee": BuyGetFree("coffee", 3, 2)} (at most one promo per item)
            self.promotions: Dict[str, BuyGetFree] = {}
            for promo in promotions or []:
                if promo.item in self.promotions:
                    raise ValueError(f"more than one promotion for {promo.item!r}")
                self.promotions[promo.item] = promo
    
            # self.counts: {"coffee": 3, "muffin": 1} (invariant: only keys with count >= 1 exist)
            self.counts: Dict[str, int] = {}
    
        def add_item(self, name: str) -> bool:
            """Add one unit of `name`; return False if blank or missing from the catalog."""
            key = normalize(name)
            if key == "" or key not in self.prices:
                return False
            self.counts[key] = self.counts.get(key, 0) + 1
            return True
    
        def remove_item(self, name: str) -> bool:
            """Remove one unit of `name`; return False if none are currently in the cart."""
            key = normalize(name)
            current_count = self.counts.get(key, 0)
            if current_count == 0:
                return False
            if current_count == 1:
                # Delete the key when count reaches 0 so receipt_lines() never prints a 0-quantity row.
                del self.counts[key]
            else:
                self.counts[key] = current_count - 1
            return True
    
        def scan(self, stream: List[str]) -> List[str]:
            """Scan a list of entries, returning rejected entries in their original form."""
            rejected: List[str] = []
            for entry in stream:
                if not self.add_item(entry):
                    rejected.append(entry)
            return rejected
    
        def quantity(self, name: str) -> int:
            """Return how many units of `name` are currently in the cart."""
            return self.counts.get(normalize(name), 0)
    
        def _charged_units(self, name: str) -> int:
            """Compute paid units dynamically from current count so removals never leave stale discounts."""
            quantity = self.counts[name]
            promo = self.promotions.get(name)
            if promo is None:
                return quantity
            return promo.charged_units(quantity)
    
        def total_cents(self) -> int:
            """Return the total amount due in cents across all items after promotions."""
            total = 0
            for name in self.counts:
                total += self.prices[name] * self._charged_units(name)
            return total
    
        def receipt_lines(self) -> List[str]:
            """Return grouped, promoted, alphabetically sorted receipt lines plus the Total line."""
            lines: List[str] = []
            # Sort item keys on demand (O(k log k) once at checkout) rather than on every scan.
            for name in sorted(self.counts):
                scanned_qty = self.counts[name]
                charged_qty = self._charged_units(name)
                unit_price_str = format_cents(self.prices[name])
                lines.append(f"{name}, {scanned_qty}, {unit_price_str} x{charged_qty}")
            lines.append(f"Total {format_cents(self.total_cents())}")
            return lines
    
        def print_receipt(self) -> None:
            """Print every line of receipt_lines() to standard output."""
            for line in self.receipt_lines():
                print(line)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of refactoring this checkout cart like upgrading a cashier from scribbling every scanned item onto a long paper tape to keeping a tidy tally card with one box per item name. Instead of hunting up the paper tape to cross an item out and recounting from the top whenever a shopper puts something back, the cashier increments or decrements that item's box in place; promotions and alphabetical ordering run only at the end when rendering the receipt.

Three naive habits introduce bugs into checkout code. First, storing prices as float uses binary floating-point representation (approximating numbers as base-2 fractions, where 0.10 + 0.20 becomes 0.30000000000000004), causing long receipts to drift by a cent; storing exact integer cents (300 for $3.00) keeps every addition exact. Second, storing a flat list of n scanned units forces remove_item and item counting to scan up to n entries instead of doing an O(1) dictionary lookup. Third, mutating stored counts or running totals when a promotion triggers during add_item makes remove_item painful to undo, whereas modeling a promotion as a pure function (a calculation depending solely on its input quantity without mutating stored state) makes removals effortless.

Walk through Example 2 with "coffee" at 300 cents ($3.00), "muffin" at 225 cents ($2.25), "pear" at 90 cents ($0.90), and BuyGetFree("coffee", buy=3, free=2): 1. Scan "coffee" five times, "muffin" once, and "pear" once: normalization (converting messy strings like " Pear " into lowercase "pear") sets counts to {"muffin": 1, "coffee": 5, "pear": 1}. 2. At receipt time, sorting keys alphabetically (["coffee", "muffin", "pear"]) evaluates "coffee" over one cycle of 3 + 2 = 5 (3 * 300 = 900 cents, "coffee, 5, 3.00 x3"), "muffin" at 225 cents, and "pear" at 90 cents, yielding "Total 12.15". 3. Call remove_item("coffee") three times and remove_item("pear") once: "pear" deletes cleanly at zero, "coffee" drops from 5 to 2, and receipt_lines() immediately recomputes min(2, 3) = 2 charged coffees ("coffee, 2, 3.00 x2", "Total 8.25") with nothing to unwind.

Complexity

Let c be the number of catalog items, p the number of configured promotions, n the total number of scanned entries, and k the number of distinct item types currently in the cart (k <= min(n, c)), assuming bounded item-name lengths.

  • ShoppingCart.__init__: O(c + p) time and space. We normalize and store the c catalog entries in self.prices and index the p promotions into self.promotions once up front.
  • add_item, remove_item, quantity: O(1) average time. Each call normalizes the item name and performs one dictionary lookup and update in self.counts (versus O(n) list search and shifting in a list-backed cart).
  • scan: O(n) time. Calls add_item once for each of the n entries in stream.
  • total_cents: O(k) time. Iterates once over the k active item types in self.counts and performs O(1) arithmetic in charged_units.
  • receipt_lines and print_receipt: O(k log k) time. Sorting the k distinct item keys takes O(k log k) comparisons, followed by O(k) string formatting.
  • itemized_receipt (Milestone 1): O(c + n) time and O(c + n) space. Normalizes the c catalog keys and emits up to n + 1 receipt lines in scan order.
  • Cart storage space: O(k) beyond the catalog. Storing one integer count per active item type uses O(k) memory regardless of how many thousands of units n were scanned.

Edge cases

  • Empty cart or empty stream: receipt_lines() and itemized_receipt([], prices) both return ["Total 0.00"].
  • Blank, whitespace-only, or unknown items ("", " ", "\t", "juice"): add_item returns False without touching self.counts, and scan returns those rejected raw strings in order.
  • Removing an absent item or removing once too many: remove_item sees current_count == 0, returns False, and leaves the cart intact.
  • Removing the final unit of an item: remove_item deletes the key from self.counts to preserve the data-structure invariant (a property guaranteed to stay true between operations) that all stored counts are >= 1, preventing "pear, 0, 0.90 x0" from appearing on the receipt.
  • Case and whitespace variants: "Coffee", " coffee ", and "COFFEE" all normalize to "coffee", merging into one grouped line and allowing remove_item(" COFFEE ") to decrement "coffee".
  • Promotion cycle boundaries: for buy=3, free=2, quantities 0..11 charge [0, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7] units — partial trailing groups charge at most 3 units before units 4 and 5 become free.
  • Malformed money inputs: to_cents rejects sub-cent strings ("3.125"), negatives ("-1.00", "-0.00"), NaN/Infinity, and non-numbers with ValueError, while format_cents(5) zero-pads single-digit cents to "0.05".

Common mistakes

  • Representing prices with float, introducing binary rounding drift (10 * 0.10 drifting from 1.00 or 0.1 + 0.2 != 0.3) instead of exact integer cents parsed via Decimal.
  • Baking promotional freebies or discounts into stored state during add_item, making remove_item error-prone when a shopper removes items across a promotion boundary.
  • Decrementing a dictionary count to 0 without deleting the key, causing receipt_lines() to emit zero-quantity rows for items already removed.
  • Hard-coding if name == "coffee": inside receipt_lines(), coupling receipt formatting to one specific deal instead of delegating to a BuyGetFree object.
  • Maintaining sorted order on every add_item / remove_item (O(k) per scan), complicating updates when sorting once on receipt_lines() (O(k log k)) is simpler and faster overall.
  • Forgetting normalize in one entry point (for example normalizing in add_item but not in ShoppingCart.__init__ or BuyGetFree.__init__), causing lookups to miss "Coffee".
  • Printing directly to stdout inside pricing logic, forcing every unit test to capture console output instead of asserting directly on receipt_lines().

Follow-up questions

  • If promotional campaigns rotate every week and multiple offers target the same SKU, how should the system source those rules and select the winning offer? Load campaigns from a database or configuration service as structured records carrying item, rule type and parameters, effective timestamps (valid_from, valid_to), a stackable flag, and a tie-break priority, injecting the active snapshot into ShoppingCart at checkout. Give every promotion class a uniform discount_cents(quantity, unit_cents) -> int method: when rules are mutually exclusive, evaluate each eligible offer against the item's count and pick the largest discount_cents (best savings for the customer, breaking ties by priority). For instance, on 5 coffees at $3.00, "buy 3 get 2 free" saves 600 cents ($6.00) whereas "10% off" saves 150 cents ($1.50), so the cart selects the 600-cent offer.
  • Suppose the store introduces a cross-product bundle deal—such as $1.00 off whenever coffee and a muffin are purchased together. How would you adapt your class design? A single-SKU charged_units(quantity) method cannot inspect other items in the basket, so bundle deals need a cart-level rule interface like apply(remaining_counts, prices) -> (discount_cents, line_text) that claims matched pairs (min(counts["coffee"], counts["muffin"]) bundles) from remaining_counts so units cannot be double-discounted. Because a cross-item savings belongs to the pair rather than either SKU alone, emit it as a dedicated discount line before Total (such as "Discount (coffee + muffin): -1.00"). Because format_cents requires non-negative cents (100 -> "1.00"), format negative discount amounts explicitly via f"-{format_cents(discount_cents)}" rather than passing -100 into integer // and %.
  • When dozens of register lanes process baskets concurrently against a shared catalog and promo table that updates mid-day, where is synchronization needed and which pricing snapshot should govern an active basket? Each register lane mutates only its own ShoppingCart instance on one thread, so cart state needs no locks. The shared catalog and promo table are read constantly by every lane and updated infrequently, so wrap both inside an immutable snapshot (a read-only object never mutated in place; mid-day updates construct a fresh snapshot behind a writer lock and atomically swap one reference). Pin that snapshot reference onto ShoppingCart when the transaction starts (or lock unit prices per scanned item if store policy honors shelf price at scan time) so a mid-transaction update never mixes pre-update and post-update rules on one receipt.
  • How do you structure automated unit tests for receipt calculation and formatting without relying on manual visual inspection of console output? Keep arithmetic and string assembly inside pure methods (total_cents() and receipt_lines() -> List[str], or typed ReceiptLine dataclasses) and write deterministic unit tests with hand-verified expectations covering empty baskets, rejected inputs, promotion cycle edges (3, 4, 5, 6 units), and scan-then-remove sequences. Combine those with property-based testing (running hundreds of seeded random add/remove traces against a simple unit-by-unit reference implementation, as in test_random_operations_match_brute_force). Reserve io.StringIO + contextlib.redirect_stdout for a single thin test verifying that print_receipt() writes each line of receipt_lines().

Follow-up questions

Similar questions

More Playstation interview questions

All 4 Playstation questions →