Object-Oriented Pizza Order Pricing Pipeline

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Problem Statement

Implement an object-oriented checkout pricing engine for a pizza shop consisting of two classes, Pizza and Order, that calculates item totals, runs four promotional rules in strict order against a running balance, and returns an itemized receipt dictionary.

Item Pricing (Pizza)

  • Supported sizes and base prices:
    • "Small": $8.00
    • "Medium": $12.00
    • "Large": $16.00
    • Passing any other size string to Pizza should raise ValueError.
  • Each topping string in toppings adds $1.50 to the pizza's price: pizza_price = base_size_price + 1.50 * len(toppings).

Sequential Promotional Pipeline (Order)

Starting from subtotal (the sum of every pizza's price in the order), maintain a running balance and evaluate Policies "A", "B", "C", and "D" strictly in order. At every stage, clamp the applied deduction to the remaining balance so no intermediate or final balance ever drops below $0.00:

  1. Policy "A" — Every Third Pizza Free: Across an order of n pizzas, the n // 3 lowest-priced pizzas overall are deducted at 100% of their full prices (any n % 3 remainder receives no Policy "A" deduction).
  2. Policy "B" — Half-Price Toppings on Multi-Large Orders: Whenever the order contains 2 or more "Large" pizzas, deduct $0.75 (50% of $1.50) per topping across every pizza in the order (including toppings on pizzas made free by Policy "A").
  3. Policy "C" — High-Spend 10% Tier: If the running balance remaining after Policies "A" and "B" is at least $50.00, deduct 10% of that remaining balance, rounding to the nearest cent with exact half-cents ($0.005) rounded up (for example, $5.375 rounds to $5.38).
  4. Policy "D" — Promo Code: If coupon_code matches "SAVE5" (exact, case-sensitive string match), deduct $5.00 from the remaining balance after Policy "C".

Required Class Signatures & Receipt Structure

class Pizza:
    def __init__(self, size: str, toppings: List[str]): ...
    def get_price(self) -> float: ...


class Order:
    def __init__(self, coupon_code: Optional[str] = None): ...
    def add_pizza(self, pizza: Pizza) -> None: ...
    def calculate_receipt(self) -> Dict: ...

calculate_receipt() must leave the order's items unchanged and return:

{
    "subtotal": float,
    "discounts": [{"policy": str, "amount": float}, ...],
    "total": float,
}
  • "policy" is "A", "B", "C", or "D", listed in evaluation order and including only policies whose applied "amount" is strictly greater than 0.00.
  • Every monetary number is rounded to 2 decimal places, satisfying subtotal - sum(d["amount"] for d in discounts) == total to the cent.

Examples

Example 1

order = Order(coupon_code="SAVE5")
order.add_pizza(Pizza("Large", ["olives", "onions", "peppers", "spinach"]))  # $22.00
order.add_pizza(Pizza("Large", ["basil", "jalapenos"]))                      # $19.00
order.add_pizza(Pizza("Small", ["garlic"]))                                  #  $9.50

order.calculate_receipt()
# Output:
# {
#     "subtotal": 50.5,
#     "discounts": [
#         {"policy": "A", "amount": 9.5},
#         {"policy": "B", "amount": 5.25},
#         {"policy": "D", "amount": 5.0},
#     ],
#     "total": 30.75,
# }

Walk-through: The three pizzas start at $22.00 + $19.00 + $9.50 = $50.50. Policy "A" makes the 3 // 3 = 1 cheapest pizza ($9.50) free, lowering the balance to $41.00. Because there are 2 "Large" pizzas, Policy "B" deducts 7 * $0.75 = $5.25 across all 7 toppings in the order, leaving $35.75. Policy "C" is skipped because $35.75 < $50.00 (even though the initial subtotal exceeded $50.00), and Policy "D" subtracts $5.00 for "SAVE5", yielding $30.75.

Example 2

order = Order()
order.add_pizza(Pizza("Large", ["bacon", "sausage", "ham", "olives", "peppers", "mushrooms"]))  # $25.00
order.add_pizza(Pizza("Large", ["spinach", "feta", "tomatoes", "onions", "garlic"]))            # $23.50
order.add_pizza(Pizza("Medium", ["basil", "jalapenos"]))                                        # $15.00
order.add_pizza(Pizza("Small", []))                                                             #  $8.00

order.calculate_receipt()
# Output:
# {
#     "subtotal": 71.5,
#     "discounts": [
#         {"policy": "A", "amount": 8.0},
#         {"policy": "B", "amount": 9.75},
#         {"policy": "C", "amount": 5.38},
#     ],
#     "total": 48.37,
# }

Walk-through: Subtotal is $25.00 + $23.50 + $15.00 + $8.00 = $71.50. Policy "A" deducts the 4 // 3 = 1 cheapest pizza ($8.00 -> $63.50). Policy "B" deducts 13 * $0.75 = $9.75 across all 13 toppings ($63.50 - $9.75 = $53.75). Because $53.75 >= $50.00, Policy "C" computes 10% ($5.375), rounds the half-cent up to $5.38, and leaves $48.37. With no coupon code, Policy "D" is omitted.

Constraints

  • Valid size values are "Small", "Medium", and "Large" (raise ValueError otherwise).
  • Each pizza has 0 <= len(toppings) <= 50 topping strings.
  • Each order contains 0 <= n <= 100 pizzas.
  • coupon_code is None or an arbitrary string.

Step-by-step walkthrough

  1. Understand the pricing pipeline and rules

    We need two classes—Pizza and Order—that compute item prices, evaluate four promotional policies sequentially against a running balance, and return an itemized receipt dictionary:

    Item prices summed  -->  subtotal
                                 |
                                 v
                           [ Policy A ]  n // 3 lowest-priced pizzas overall are free
                                 |
                                 v
                           [ Policy B ]  2+ Large pizzas -> $0.75 off every topping in the order
                                 |
                                 v
                           [ Policy C ]  Running balance >= $50.00 -> 10% off remaining balance
                                 |
                                 v
                           [ Policy D ]  Coupon "SAVE5" -> $5.00 off remaining balance
                                 |
                                 v
                             final total (clamped so balance never drops below $0.00)
    

    Pin down the exact edge rules before coding:

    • Policy labels and positive-only lines: Each entry in "discounts" uses "A", "B", "C", or "D" and appears only when its applied deduction exceeds $0.00.
    • Policy A inspects the entire basket: Across n pizzas, the n // 3 lowest-priced pizzas overall are free (not the cheapest within each chronological group of 3), and any n % 3 leftover pizzas get no Policy A deduction.
    • Policy B counts every topping in the order: Whenever at least 2 "Large" pizzas are present, $0.75 is deducted per topping across all pizzas—including toppings on pizzas made free by Policy A.
    • Policy C checks the post-A/B running balance: As in Example 1, an order whose initial subtotal is $50.50 but drops to $35.75 after Policies A and B does not qualify for Policy C.
    • Zero-dollar floor: At every step, clamp the deduction to the current running balance so neither intermediate nor final balances ever become negative.
  2. Why we compute in integer cents instead of floats

    Python float values store base-2 fractions, which cannot represent most decimal cents exactly (0.1 + 0.2 == 0.30000000000000004). Worse, Python's round(..., 2) uses round-half-to-even on binary approximations (round(51.25 * 0.10, 2) yields 5.12, whereas round(53.75 * 0.10, 2) yields 5.38), and subtracting rounded floats can make subtotal - sum(discounts) disagree with total by $0.01.

    Because every menu price and per-topping deduction is an exact whole number of cents ($8.00 = 800, $1.50 = 150, $0.75 = 75), performing all internal arithmetic in int cents—and converting to dollar floats once at the output boundary—keeps every receipt 100% exact to the penny.

    SIZE_PRICE_CENTS = {
        "Small": 800,
        "Medium": 1200,
        "Large": 1600,
    }
    TOPPING_PRICE_CENTS = 150
    TOPPING_DISCOUNT_CENTS = 75
    TIER_THRESHOLD_CENTS = 5000
    VALID_COUPON_CODE = "SAVE5"
    COUPON_DISCOUNT_CENTS = 500
    
    
    def cents_to_dollars(cents: int) -> float:
        """Convert an exact integer cent amount into a two-decimal dollar float."""
        return round(cents / 100, 2)
    
  3. Build the `Pizza` model

    Pizza validates size, stores a defensive copy of toppings (list(toppings)) so later caller mutations cannot alter an already-added pizza's price, and exposes price_cents() -> int internally alongside public get_price() -> float:

    from typing import List
    
    
    class Pizza:
        def __init__(self, size: str, toppings: List[str]):
            if size not in SIZE_PRICE_CENTS:
                raise ValueError(f"Unknown pizza size: {size!r}")
            self.size = size
            # Copy the caller's list so mutating the original list later cannot alter this pizza's price.
            self.toppings = list(toppings)
    
        def price_cents(self) -> int:
            """Exact pizza price in integer cents: base size price + 150 cents per topping."""
            base_cents = SIZE_PRICE_CENTS[self.size]
            toppings_cents = TOPPING_PRICE_CENTS * len(self.toppings)
            return base_cents + toppings_cents
    
        def get_price(self) -> float:
            return cents_to_dollars(self.price_cents())
    
  4. Isolate each promotional rule behind one function signature

    Giving all four rules one uniform signature—(pizzas, balance_cents, coupon_code) -> raw_discount_cents—cleanly separates rule math from balance clamping:

    • Policy A (policy_a_free_pizzas): Collect all pizza prices in cents, sort ascending, and sum the first len(pizzas) // 3 values.
    • Policy B (policy_b_topping_special): Count "Large" pizzas and total toppings across all pizzas; return 75 * total_toppings when large_count >= 2, else 0.
    • Policy C (policy_c_tier_percentage): Return 0 when balance_cents < 5000. Otherwise compute 10% with half-cents (0.5c) rounded up using pure integer math (balance_cents + 5) // 10:
      • balance_cents = 5374 (10% = 537.4c) -> (5374 + 5) // 10 = 537c ($5.37).
      • balance_cents = 5375 (10% = 537.5c) -> (5375 + 5) // 10 = 538c ($5.38).
    • Policy D (policy_d_fixed_coupon): Return 500 cents when coupon_code == "SAVE5", else 0.
    from typing import List, Optional
    
    
    def policy_a_free_pizzas(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy A: Across every 3 pizzas in the order, the lowest-priced pizza overall is free."""
        # price_cents_list: ascending list of individual pizza prices in cents, e.g., [950, 1900, 2200].
        price_cents_list = []
        for pizza in pizzas:
            price_cents_list.append(pizza.price_cents())
        price_cents_list.sort()
    
        # Integer division drops leftover pizzas (< 3).
        free_count = len(price_cents_list) // 3
        free_total_cents = 0
        for i in range(free_count):
            free_total_cents += price_cents_list[i]
        return free_total_cents
    
    
    def policy_b_topping_special(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy B: With 2+ Large pizzas, every topping in the order gets $0.75 (50%) off."""
        large_count = 0
        total_toppings = 0
        for pizza in pizzas:
            if pizza.size == "Large":
                large_count += 1
            # Count toppings on every pizza in the order, including pizzas discounted by Policy A.
            total_toppings += len(pizza.toppings)
    
        if large_count < 2:
            return 0
        return TOPPING_DISCOUNT_CENTS * total_toppings
    
    
    def policy_c_tier_percentage(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy C: If remaining balance after A and B is at least $50.00, deduct 10%."""
        # Use strict `<` so a balance of exactly 5000 cents ($50.00) still qualifies.
        if balance_cents < TIER_THRESHOLD_CENTS:
            return 0
    
        # Compute 10% of balance_cents rounded to the nearest cent with half-cents (0.5) rounded up:
        # adding 5 before integer division by 10 turns e.g. 5375 (537.5 cents) into 5380 // 10 == 538.
        return (balance_cents + 5) // 10
    
    
    def policy_d_fixed_coupon(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy D: Exact coupon code 'SAVE5' deducts $5.00 (500 cents)."""
        if coupon_code == VALID_COUPON_CODE:
            return COUPON_DISCOUNT_CENTS
        return 0
    
  5. Run the sequential pipeline with clamping in `Order`

    Order.calculate_receipt() walks POLICIES from "A" to "D", clamping each raw discount via applied_cents = min(raw_discount_cents, balance_cents) and recording only strictly positive deductions without mutating self.pizzas:

    from typing import Dict, List, Optional
    
    POLICIES = [
        ("A", policy_a_free_pizzas),
        ("B", policy_b_topping_special),
        ("C", policy_c_tier_percentage),
        ("D", policy_d_fixed_coupon),
    ]
    
    
    class Order:
        def __init__(self, coupon_code: Optional[str] = None):
            self.coupon_code = coupon_code
            # self.pizzas: list of Pizza objects in insertion order; never mutated during pricing.
            self.pizzas: List[Pizza] = []
    
        def add_pizza(self, pizza: Pizza) -> None:
            self.pizzas.append(pizza)
    
        def calculate_receipt(self) -> Dict:
            # Phase 1: Sum all original pizza prices in integer cents.
            subtotal_cents = 0
            for pizza in self.pizzas:
                subtotal_cents += pizza.price_cents()
    
            # Phase 2: Walk policies A -> B -> C -> D against a running balance in cents.
            balance_cents = subtotal_cents
            # discounts: list of {"policy": "A", "amount": 9.5} dicts for strictly positive deductions.
            discounts = []
    
            for policy_name, policy_fn in POLICIES:
                raw_discount_cents = policy_fn(self.pizzas, balance_cents, self.coupon_code)
                # Clamp against balance_cents inside the loop so no intermediate or final balance drops below 0.
                applied_cents = min(raw_discount_cents, balance_cents)
    
                # Only record policies that actually reduced the balance by more than $0.00.
                if applied_cents > 0:
                    balance_cents -= applied_cents
                    discounts.append({
                        "policy": policy_name,
                        "amount": cents_to_dollars(applied_cents),
                    })
    
            # Phase 3: Convert integer cents to dollar floats once at the boundary so lines sum to total.
            return {
                "subtotal": cents_to_dollars(subtotal_cents),
                "discounts": discounts,
                "total": cents_to_dollars(balance_cents),
            }
    
  6. Trace Example 1 and Example 2 step by step

    First, trace Example 1 (Large + 4 toppings, Large + 2 toppings, Small + 1 topping, coupon "SAVE5"):

    Pizza prices:  1600 + 600 = 2200c,  1600 + 300 = 1900c,  800 + 150 = 950c
    Subtotal:      2200 + 1900 + 950 = 5050c ($50.50)
    
    Policy A:  3 // 3 = 1 free pizza -> lowest price is 950c ($9.50)
               balance_cents = 5050 - 950 = 4100c ($41.00)
    Policy B:  2 Large pizzas (>= 2), 7 total toppings * 75c = 525c ($5.25)
               balance_cents = 4100 - 525 = 3575c ($35.75)
    Policy C:  balance_cents = 3575 < 5000 -> 0c (omitted even though subtotal was $50.50!)
    Policy D:  coupon "SAVE5" -> min(500, 3575) = 500c ($5.00)
               balance_cents = 3575 - 500 = 3075c ($30.75)
    
    Receipt:   subtotal = 50.5, discounts = [A: 9.5, B: 5.25, D: 5.0], total = 30.75
    Check:     50.50 - (9.50 + 5.25 + 5.00) = 30.75
    

    Second, trace Example 2 (Large + 6 toppings, Large + 5 toppings, Medium + 2 toppings, Small + 0 toppings, no coupon):

    Pizza prices:  2500c, 2350c, 1500c, 800c
    Subtotal:      2500 + 2350 + 1500 + 800 = 7150c ($71.50)
    
    Policy A:  4 // 3 = 1 free pizza -> lowest price is 800c ($8.00)
               balance_cents = 7150 - 800 = 6350c ($63.50)
    Policy B:  2 Large pizzas, 13 toppings * 75c = 975c ($9.75)
               balance_cents = 6350 - 975 = 5375c ($53.75)
    Policy C:  5375 >= 5000 -> (5375 + 5) // 10 = 538c ($5.38, rounding $5.375 half-up)
               balance_cents = 5375 - 538 = 4837c ($48.37)
    Policy D:  coupon_code is None -> 0c (omitted)
    
    Check:     71.50 - (8.00 + 9.75 + 5.38) = 48.37 (exact to the penny!)
    
  7. Complete solution

    from typing import Dict, List, Optional
    
    # Store all monetary constants as exact integer cents so binary floating-point
    # inaccuracies (like 0.1 + 0.2 == 0.30000000000000004) never cause 1-cent drift.
    # SIZE_PRICE_CENTS: maps size name -> base pizza price in cents (e.g., "Small" -> 800).
    SIZE_PRICE_CENTS = {
        "Small": 800,
        "Medium": 1200,
        "Large": 1600,
    }
    TOPPING_PRICE_CENTS = 150
    TOPPING_DISCOUNT_CENTS = 75
    TIER_THRESHOLD_CENTS = 5000
    VALID_COUPON_CODE = "SAVE5"
    COUPON_DISCOUNT_CENTS = 500
    
    
    def cents_to_dollars(cents: int) -> float:
        """Convert an exact integer cent amount into a two-decimal dollar float."""
        return round(cents / 100, 2)
    
    
    class Pizza:
        def __init__(self, size: str, toppings: List[str]):
            if size not in SIZE_PRICE_CENTS:
                raise ValueError(f"Unknown pizza size: {size!r}")
            self.size = size
            # Copy the caller's list so mutating the original list later cannot alter this pizza's price.
            self.toppings = list(toppings)
    
        def price_cents(self) -> int:
            """Exact pizza price in integer cents: base size price + 150 cents per topping."""
            base_cents = SIZE_PRICE_CENTS[self.size]
            toppings_cents = TOPPING_PRICE_CENTS * len(self.toppings)
            return base_cents + toppings_cents
    
        def get_price(self) -> float:
            return cents_to_dollars(self.price_cents())
    
    
    # Every discount policy function shares one uniform signature:
    #   (pizzas, balance_cents, coupon_code) -> raw_discount_cents
    # Keeping each rule in its own function isolates the policy math from balance clamping.
    
    def policy_a_free_pizzas(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy A: Across every 3 pizzas in the order, the lowest-priced pizza overall is free."""
        # price_cents_list: ascending list of individual pizza prices in cents, e.g., [950, 1900, 2200].
        price_cents_list = []
        for pizza in pizzas:
            price_cents_list.append(pizza.price_cents())
        price_cents_list.sort()
    
        # Integer division drops leftover pizzas (< 3).
        free_count = len(price_cents_list) // 3
        free_total_cents = 0
        for i in range(free_count):
            free_total_cents += price_cents_list[i]
        return free_total_cents
    
    
    def policy_b_topping_special(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy B: With 2+ Large pizzas, every topping in the order gets $0.75 (50%) off."""
        large_count = 0
        total_toppings = 0
        for pizza in pizzas:
            if pizza.size == "Large":
                large_count += 1
            # Count toppings on every pizza in the order, including pizzas discounted by Policy A.
            total_toppings += len(pizza.toppings)
    
        if large_count < 2:
            return 0
        return TOPPING_DISCOUNT_CENTS * total_toppings
    
    
    def policy_c_tier_percentage(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy C: If remaining balance after A and B is at least $50.00, deduct 10%."""
        # Use strict `<` so a balance of exactly 5000 cents ($50.00) still qualifies.
        if balance_cents < TIER_THRESHOLD_CENTS:
            return 0
    
        # Compute 10% of balance_cents rounded to the nearest cent with half-cents (0.5) rounded up:
        # adding 5 before integer division by 10 turns e.g. 5375 (537.5 cents) into 5380 // 10 == 538.
        return (balance_cents + 5) // 10
    
    
    def policy_d_fixed_coupon(pizzas: List[Pizza], balance_cents: int, coupon_code: Optional[str]) -> int:
        """Policy D: Exact coupon code 'SAVE5' deducts $5.00 (500 cents)."""
        if coupon_code == VALID_COUPON_CODE:
            return COUPON_DISCOUNT_CENTS
        return 0
    
    
    # POLICIES: ordered pipeline of (policy_label, policy_fn) evaluated strictly from A to D.
    POLICIES = [
        ("A", policy_a_free_pizzas),
        ("B", policy_b_topping_special),
        ("C", policy_c_tier_percentage),
        ("D", policy_d_fixed_coupon),
    ]
    
    
    class Order:
        def __init__(self, coupon_code: Optional[str] = None):
            self.coupon_code = coupon_code
            # self.pizzas: list of Pizza objects in insertion order; never mutated during pricing.
            self.pizzas: List[Pizza] = []
    
        def add_pizza(self, pizza: Pizza) -> None:
            self.pizzas.append(pizza)
    
        def calculate_receipt(self) -> Dict:
            # Phase 1: Sum all original pizza prices in integer cents.
            subtotal_cents = 0
            for pizza in self.pizzas:
                subtotal_cents += pizza.price_cents()
    
            # Phase 2: Walk policies A -> B -> C -> D against a running balance in cents.
            balance_cents = subtotal_cents
            # discounts: list of {"policy": "A", "amount": 9.5} dicts for strictly positive deductions.
            discounts = []
    
            for policy_name, policy_fn in POLICIES:
                raw_discount_cents = policy_fn(self.pizzas, balance_cents, self.coupon_code)
                # Clamp against balance_cents inside the loop so no intermediate or final balance drops below 0.
                applied_cents = min(raw_discount_cents, balance_cents)
    
                # Only record policies that actually reduced the balance by more than $0.00.
                if applied_cents > 0:
                    balance_cents -= applied_cents
                    discounts.append({
                        "policy": policy_name,
                        "amount": cents_to_dollars(applied_cents),
                    })
    
            # Phase 3: Convert integer cents to dollar floats once at the boundary so lines sum to total.
            return {
                "subtotal": cents_to_dollars(subtotal_cents),
                "discounts": discounts,
                "total": cents_to_dollars(balance_cents),
            }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a checkout register that scans all items in your cart once to establish the starting bill, then walks down a fixed four-step promotion checklist (A -> B -> C -> D). Each promotion inspects the basket and the current unpaid balance, proposes a deduction, and the register subtracts min(proposed, balance)—never allowing the unpaid balance to dip below $0.00—before advancing to the next promotion.

Implementing this directly with binary floating-point numbers (float, which stores base-2 approximations of decimal fractions) inside one big if/else method introduces two classic bugs. First, float multiplication and round(..., 2) treat half-cents inconsistently (round(51.25 * 0.10, 2) yields 5.12, while round(53.75 * 0.10, 2) yields 5.38), and accumulated rounding error can make subtotal - sum(discounts) miss total by $0.01. Second, tangling all four promotions inside calculate_receipt() makes it easy to accidentally test Policy C against the original subtotal instead of the post-A/B running balance.

Computing everything in integer cents ($1.00 = 100 cents) and isolating each rule into a uniform function eliminates both problems. Walk through Example 1 (Large + 4 toppings = 2200c, Large + 2 toppings = 1900c, Small + 1 topping = 950c, coupon "SAVE5"): 1. Subtotal starts at 2200 + 1900 + 950 = 5050 cents ($50.50). 2. Policy A sorts [950, 1900, 2200], sees 3 // 3 = 1 free item, and deducts 950c -> running balance becomes 4100c. 3. Policy B sees 2 Large pizzas and 7 total toppings, deducting 7 * 75 = 525c -> running balance becomes 3575c. 4. Policy C checks 3575 >= 5000, sees it is false (even though subtotal was 5050c), and deducts 0c (omitted). 5. Policy D matches "SAVE5" and deducts 500c -> final total is 3075c ($30.75).

Complexity

  • Time:
    • Pizza.__init__ runs in O(t) time for t toppings on that pizza because it makes a shallow copy of toppings. Pizza.get_price() runs in O(1) time.
    • Order.add_pizza runs in amortized O(1) time (occasional list growth averages out to constant cost per append).
    • Order.calculate_receipt runs in O(n log n) time for n pizzas: summing the subtotal is O(n), Policy A sorts n integer prices in O(n log n), Policy B scans the n pizzas in O(n), and Policies C and D each run in O(1). With n <= 100, O(n log n) finishes in microseconds.
  • Space: calculate_receipt allocates O(n) auxiliary memory for price_cents_list in Policy A, plus O(1) space for "discounts" (at most 4 dictionaries).

Edge cases

  • Empty order with "SAVE5": subtotal_cents = 0; Policy D's 500c deduction is clamped via min(500, 0) to 0c, producing "discounts": [] and "total": 0.0.
  • Fewer than 3 pizzas or remainder items: Integer division n // 3 yields 0 free pizzas for 1 or 2 items and 1 free pizza for 4 or 5 items.
  • Running balance of exactly $50.00: Policy C checks balance_cents < 5000, so 5000c ($50.00) qualifies for the $5.00 (10%) tier deduction.
  • Initial subtotal >= $50.00, post-A/B balance < $50.00: As in Example 1 ($50.50 dropping to $35.75), Policy C evaluates the post-A/B balance and skips the 10% deduction.
  • Half-cent rounding on Policy C: Whenever balance_cents ends in 5 (such as 5375c = $53.75 in Example 2), 10% is 537.5 cents ($5.375). Integer arithmetic (balance_cents + 5) // 10 rounds half-cents up to 538c ($5.38) and subtracts that exact cent amount so the receipt reconciles to the penny.
  • Ties among cheapest pizzas: Because Policy A sums the n // 3 smallest prices and Policy B counts toppings across the entire order regardless of which pizza was free, price ties never change any discount line.
  • Repeated calculate_receipt() calls: Pricing never mutates self.pizzas, so recomputing receipts before and after adding more pizzas always stays accurate.

Common mistakes

  • Doing arithmetic in float throughout: Subtracting rounded floats step by step can introduce binary representation drift where subtotal - sum(discounts) differs from total by $0.01.
  • Testing Policy C against the pre-discount subtotal rather than the balance remaining after Policies A and B.
  • Grouping pizzas in insertion chunks of 3 for Policy A: Ordering 6 pizzas makes the 2 lowest-priced pizzas across all 6 items free, not the cheapest of items 1..3 plus the cheapest of items 4..6.
  • Emitting $0.00 entries in "discounts": Any promotion whose clamped deduction equals 0 must be excluded from "discounts".
  • Mutating self.pizzas while computing Policy A: Sorting or popping self.pizzas directly corrupts subsequent calculate_receipt() calls.

Follow-up questions

  • How could you apply Strategy or Chain of Responsibility so promotional rule order can be reconfigured from external data without code changes? Under the Strategy pattern (encapsulating each interchangeable rule inside its own object behind a shared interface), define a DiscountPolicy protocol with compute_cents(order_ctx) -> int and register concrete strategies in a lookup table POLICY_REGISTRY = {"A": FreeThirdPizzaPolicy(), "B": HalfPriceToppingPolicy(), ...}. Loading an ordered rule list such as ["B", "A", "C", "D"] from a database row or JSON config lets operators reorder or toggle promotions at runtime without redeploying code. When rules also need short-circuiting (for instance, an exclusive promo code that halts downstream discounts), the Chain of Responsibility pattern (where each handler updates the context and decides whether to invoke the next handler or stop) adds a halt_pipeline: bool flag cleanly.

  • How would you track item-level discount state if toppings on a free Policy A pizza were excluded from Policy B's half-off promotion? Create per-calculation LineItem(pizza, original_idx, is_free=False) wrappers inside calculate_receipt. Sort those wrappers by (pizza.price_cents(), original_idx)—using original_idx for deterministic tie-breaking (note that distinct pizza sizes here cannot even tie in price because $4.00 and $8.00 base-price gaps are not multiples of $1.50, so tied pizzas always have identical topping counts)—and set is_free = True on the first n // 3 wrappers. Policy B then checks the 2+ Large condition and sums len(item.pizza.toppings) exclusively across wrappers with not item.is_free. If downstream tax or partial-refund logic also needs basket-wide discounts C and D split across paid items, allocate cents proportionally via the largest-remainder method (flooring each item's fractional share and distributing leftover pennies to the items with the largest fractional remainders).

  • Why does representing money in integer cents eliminate binary floating-point drift, and how should fractional-cent percentage discounts be rounded? IEEE-754 binary floats cannot represent decimal fractions like 0.10 or 0.01 exactly in base 2, so repeated additions and multiplications accumulate tiny representation errors that flip rounding boundaries unpredictably. Storing every price, balance, and deduction as an exact int count of cents makes addition, subtraction, and whole-cent multiplication 100% exact, confining rounding to explicit percentage divisions like Policy C's 10%. At those percentage steps, enforce one explicit rule—such as round half up ((balance_cents + 5) // 10) or banker's rounding / round half to even (rounding exact .5 ties to the nearest even cent to eliminate systematic upward bias across millions of transactions)—and subtract that exact integer cent deduction from balance_cents so line items and totals always sum identically.

Alternative approaches

  • Base-10 decimal.Decimal arithmetic: Representing prices as Decimal("16.00") and Decimal("1.50") with quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) avoids binary float issues directly in decimal dollars, trading slightly heavier object overhead for explicit accounting rounding modes.
  • Heap selection (heapq.nsmallest) for Policy A: Finding the k = n // 3 smallest prices via a min-heap runs in O(n log k) (or O(n) average via quickselect, a partial-partitioning algorithm), which only matters if basket sizes grow far beyond n <= 100.

Follow-up questions

Similar questions

More American interview questions

All 5 American questions →