Cart Checkout Pricing with Half-to-Even Unit Vouchers

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Implement the billing calculator for a retail point-of-sale system where shoppers buy line items in bulk and redeem single-unit promotional vouchers. Given cart and coupons, return the total amount owed in integer cents.

def calculate_cart_total(cart: list[dict], coupons: list[dict]) -> int:

Input Record Formats

Each dictionary in cart contains: - item_id (str): Identifier of the product on this line. - unit_price_cents (int): Regular price of one unit in cents. - quantity (int): Number of units purchased on this line.

Each dictionary in coupons contains: - coupon_id (str): Identifier of the voucher. - item_id (str): Product identifier that this voucher targets. - discount_type (str): Either "PERCENT" or "FIXED". - discount_value (int): An integer percentage in 1..100 when discount_type == "PERCENT", or a cent deduction per unit when discount_type == "FIXED".

Pricing & Redemption Rules

  1. Single-unit limit: Every voucher discounts at most one individual unit of its target item_id. A voucher cannot be reused or split across multiple units; when quantity exceeds the count of matching vouchers, the remaining units are billed at unit_price_cents.
  2. Unused vouchers: Vouchers targeting an item_id absent from cart, as well as extra vouchers left over once every unit of that item_id already has a voucher, are ignored.
  3. Zero-cent unit floor: A discounted unit's charge is max(0, unit_price_cents - discount_cents). Excess deduction on one unit never reduces the cost of any other unit.
  4. Banker's rounding on percentages: When discount_type == "PERCENT", compute the exact cent deduction (unit_price_cents * discount_value) / 100 and round fractional cents to the closest integer using round-half-to-even: if the fraction is .5 on the nose, round toward whichever adjacent integer is even (for instance, 14.5 rounds to 14, while 15.5 rounds to 16).
  5. Sequential voucher priority: When multiple vouchers target the same item_id, redeem them in the exact order they appear in coupons.

Examples

Example 1

cart = [
    {"item_id": "notebook", "unit_price_cents": 290, "quantity": 2},
    {"item_id": "pen", "unit_price_cents": 120, "quantity": 1},
]
coupons = [
    {"coupon_id": "v1", "item_id": "notebook", "discount_type": "PERCENT", "discount_value": 5},
    {"coupon_id": "v2", "item_id": "eraser", "discount_type": "FIXED", "discount_value": 40},
]
# Output: 686
  • Voucher "v2" targets "eraser", which is not in cart, so it is skipped.
  • Unit 1 of "notebook" gets 5% off 290 cents: 290 * 5 / 100 = 14.5 cents, which rounds half-to-even to 14 cents, leaving 290 - 14 = 276 cents.
  • Unit 2 of "notebook" pays full price (290 cents), and "pen" costs 120 cents, totaling 276 + 290 + 120 = 686 cents.

Example 2

cart = [
    {"item_id": "lamp", "unit_price_cents": 310, "quantity": 1},
]
coupons = [
    {"coupon_id": "v1", "item_id": "lamp", "discount_type": "PERCENT", "discount_value": 5},
]
# Output: 294

310 * 5 / 100 = 15.5 cents; round-half-to-even rounds 15.5 up to even 16 cents, giving 310 - 16 = 294 cents.

Example 3

cart = [
    {"item_id": "cable", "unit_price_cents": 400, "quantity": 3},
]
coupons = [
    {"coupon_id": "k1", "item_id": "cable", "discount_type": "FIXED", "discount_value": 90},
    {"coupon_id": "k2", "item_id": "cable", "discount_type": "PERCENT", "discount_value": 30},
    {"coupon_id": "k3", "item_id": "cable", "discount_type": "FIXED", "discount_value": 650},
    {"coupon_id": "k4", "item_id": "cable", "discount_type": "FIXED", "discount_value": 50},
]
# Output: 590

The three units redeem "k1" (400 - 90 = 310), "k2" (400 - 120 = 280), and "k3" (max(0, 400 - 650) = 0) in input order, while "k4" is ignored as surplus, totaling 310 + 280 + 0 = 590 cents.

Example 4

cart = [
    {"item_id": "bolt", "unit_price_cents": 35, "quantity": 4},
    {"item_id": "wrench", "unit_price_cents": 1250, "quantity": 1},
]
coupons = []
# Output: 1390

With no vouchers provided, every unit pays full price: 4 * 35 + 1 * 1250 = 1390 cents.

Constraints

  • 0 <= len(cart) <= 10^4
  • 0 <= len(coupons) <= 10^4
  • 1 <= unit_price_cents <= 10^6
  • 1 <= quantity <= 10^4
  • 1 <= discount_value <= 100 when discount_type == "PERCENT"
  • 1 <= discount_value <= 10^6 when discount_type == "FIXED"

Step-by-step walkthrough

  1. Understand the billing rules

    Given cart lines (item_id, unit_price_cents, quantity) and coupons (coupon_id, item_id, discount_type, discount_value), we need to compute the final bill in integer cents.

    Every detail reduces to four clean invariants:

    • One voucher per unit, in list order: each voucher applies to at most one unit of its item_id, redeemed in the exact order vouchers appear in coupons.
    • Skip unmatched or surplus vouchers: vouchers targeting products absent from cart, or vouchers left over past quantity, have no effect.
    • Per-unit zero floor: a discounted unit pays max(0, unit_price_cents - discount_cents) — unused deduction never spills onto other units.
    • Half-to-even rounding on percentages: a "PERCENT" deduction equals (unit_price_cents * discount_value) / 100 rounded to the closest cent with round-half-to-even (exact .5 ties pick the even integer neighbor: 14.5 -> 14, 15.5 -> 16).
  2. Why expanding every unit is too slow

    A literal unit-by-unit simulation creates one record per physical item unit, scans coupons attaching each voucher to the first un-discounted unit of that product, and sums the unit charges.

    While fine on tiny carts, len(cart) can reach 10^4 and each line's quantity can also reach 10^4. Materializing 10^4 * 10^4 = 10^8 unit records blows through memory and time limits in Python. Yet len(coupons) <= 10^4: out of 10^8 units, at most 10,000 ever receive a discount!

  3. Key insight: group vouchers by product and batch full-price units

    Every unit on a cart line shares the same unit_price_cents, so un-discounted units never need individual records:

    1. Bucket coupons into a dictionary coupons_by_item[item_id] preserving input order. Each list acts like a queue of vouchers waiting for units of that product.
    2. When billing a cart line with quantity units, consume discounted_units = min(quantity, available_coupons) vouchers from that product's queue and price those units one by one.
    3. Bill all remaining quantity - discounted_units full-price units in one O(1) multiplication (quantity - discounted_units) * unit_price.
    Cart line: "notebook", unit_price = 290, quantity = 10,000
    Voucher queue for "notebook": [v1 (5% off), v3 (40 cents off)]
    
      Unit 1  <-- v1 (priced individually)
      Unit 2  <-- v3 (priced individually)
      Units 3..10,000 (9,998 units) --> 9,998 * 290 in one step!
    

    Maintaining next_coupon_idx[item_id] (the next unused index in coupons_by_item[item_id]) also handles carts where the same item_id appears across multiple lines without ever double-spending a voucher.

  4. Exact banker's rounding with integer arithmetic

    Python's built-in round() implements round-half-to-even, making floating-point math look tempting. The catch is that binary IEEE-754 floats cannot represent most decimal hundredths like 0.14 or 0.70 exactly:

    75 * (14 / 100)  in float  -->  10.500000000000002  -->  round() gives 11 (WRONG: 10.5 must round to even 10)
    45 * (70 / 100)  in float  -->  31.499999999999996  -->  round() gives 31 (WRONG: 31.5 must round to even 32)
    

    We eliminate floating-point drift completely by computing in hundredths of a cent. Because unit_price_cents and discount_value are integers, hundredths_of_cent = unit_price_cents * discount_value is exact. Splitting by 100 via quotient, remainder = divmod(hundredths_of_cent, 100) pinpoints where the fraction sits relative to .50:

    hundredths_of_cent = 100 * quotient + remainder   (0 <= remainder <= 99)
    
      remainder < 50   -->  below .50, round down to quotient
      remainder > 50   -->  above .50, round up to quotient + 1
      remainder == 50  -->  exact .50 tie:
                              if quotient is even -> keep quotient       (14.50 -> 14)
                              if quotient is odd  -> bump to quotient + 1 (15.50 -> 16)
    

    Here is that integer rounder alongside discounted_unit_price, which enforces the 0-cent floor per unit:

    def divide_by_100_half_even(hundredths_of_cent: int) -> int:
        """Divide a non-negative integer by 100 and round to nearest integer, ties to even."""
        # Split exact hundredths into whole cents (quotient) and leftover hundredths (0..99).
        quotient, remainder = divmod(hundredths_of_cent, 100)
    
        # Strictly above 0.50 cents rounds up; strictly below 0.50 cents rounds down.
        if remainder > 50:
            return quotient + 1
        if remainder < 50:
            return quotient
    
        # Exact 0.50-cent tie (remainder == 50): banker's rounding picks the even neighbor.
        # If quotient is odd, quotient + 1 is even; otherwise quotient is already even.
        if quotient % 2 == 1:
            return quotient + 1
        return quotient
    
    
    def discounted_unit_price(unit_price_cents: int, coupon: dict) -> int:
        """Return the price in cents of one unit after applying one coupon (floored at 0)."""
        if coupon["discount_type"] == "PERCENT":
            # Multiply in exact integers first so binary float inaccuracies never distort 0.5 ties.
            raw_hundredths = unit_price_cents * coupon["discount_value"]
            discount_cents = divide_by_100_half_even(raw_hundredths)
        else:
            discount_cents = coupon["discount_value"]
    
        # Clamp each individual unit's post-discount price at 0 cents.
        return max(0, unit_price_cents - discount_cents)
    
  5. Match vouchers to cart lines in list order

    Next, bucket vouchers by item_id, step through cart, redeem discounted_units vouchers per line, and multiply out any remaining full-price units:

    from typing import Dict, List
    
    
    def calculate_cart_total(cart: list[dict], coupons: list[dict]) -> int:
        # coupons_by_item: maps item_id -> ordered list of coupon dicts for that item,
        # e.g. {"notebook": [{"coupon_id": "v1", ...}, {"coupon_id": "v3", ...}]}
        coupons_by_item: Dict[str, List[dict]] = {}
        for coupon in coupons:
            item_id = coupon["item_id"]
            if item_id not in coupons_by_item:
                coupons_by_item[item_id] = []
            coupons_by_item[item_id].append(coupon)
    
        # next_coupon_idx: maps item_id -> index of the next unused coupon in coupons_by_item[item_id]
        next_coupon_idx: Dict[str, int] = {}
        total_cents = 0
    
        # Phase 2: price each cart line without looping over individual full-price units.
        for line in cart:
            item_id = line["item_id"]
            unit_price = line["unit_price_cents"]
            quantity = line["quantity"]
    
            item_coupons = coupons_by_item.get(item_id, [])
            start_idx = next_coupon_idx.get(item_id, 0)
            available_coupons = len(item_coupons) - start_idx
    
            # Redeem at most one coupon per unit in list order; surplus coupons are ignored.
            discounted_units = min(quantity, available_coupons)
            for idx in range(start_idx, start_idx + discounted_units):
                total_cents += discounted_unit_price(unit_price, item_coupons[idx])
            next_coupon_idx[item_id] = start_idx + discounted_units
    
            # All remaining units on this line pay full price in one O(1) multiplication.
            full_price_units = quantity - discounted_units
            total_cents += full_price_units * unit_price
    
        return total_cents
    

    Vouchers whose item_id never occurs in cart stay untouched in coupons_by_item.

  6. Trace Example 1 and Example 3

    Example 1:
      coupons_by_item = {"notebook": [v1 (PERCENT 5)], "eraser": [v2 (FIXED 40)]}
    
      Line 1 ("notebook", price = 290, qty = 2):
        discounted_units = min(2, 1) = 1
        Unit 1 with v1: raw_hundredths = 290 * 5 = 1450 -> divmod(1450, 100) = (14, 50)
                        tie with even quotient 14 -> discount = 14 -> unit pays 290 - 14 = 276
        Full-price units: (2 - 1) * 290 = 290
        Running total = 276 + 290 = 566
    
      Line 2 ("pen", price = 120, qty = 1):
        discounted_units = min(1, 0) = 0
        Full-price units: 1 * 120 = 120
        Running total = 566 + 120 = 686   ("eraser" voucher v2 is never used)
    
    Example 3 (3 units of "cable" at 400 cents; vouchers FIXED 90, PERCENT 30, FIXED 650, FIXED 50):
      discounted_units = min(3, 4) = 3  (4th voucher FIXED 50 is ignored as surplus)
      Unit 1: max(0, 400 - 90)  = 310
      Unit 2: max(0, 400 - 120) = 280
      Unit 3: max(0, 400 - 650) = 0     (floored at 0 per unit; does NOT reduce Units 1 or 2)
      Total = 310 + 280 + 0 = 590
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def divide_by_100_half_even(hundredths_of_cent: int) -> int:
        """Divide a non-negative integer by 100 and round to nearest integer, ties to even."""
        # Split exact hundredths into whole cents (quotient) and leftover hundredths (0..99).
        quotient, remainder = divmod(hundredths_of_cent, 100)
    
        # Strictly above 0.50 cents rounds up; strictly below 0.50 cents rounds down.
        if remainder > 50:
            return quotient + 1
        if remainder < 50:
            return quotient
    
        # Exact 0.50-cent tie (remainder == 50): banker's rounding picks the even neighbor.
        # If quotient is odd, quotient + 1 is even; otherwise quotient is already even.
        if quotient % 2 == 1:
            return quotient + 1
        return quotient
    
    
    def discounted_unit_price(unit_price_cents: int, coupon: dict) -> int:
        """Return the price in cents of one unit after applying one coupon (floored at 0)."""
        if coupon["discount_type"] == "PERCENT":
            # Multiply in exact integers first so binary float inaccuracies never distort 0.5 ties.
            raw_hundredths = unit_price_cents * coupon["discount_value"]
            discount_cents = divide_by_100_half_even(raw_hundredths)
        else:
            discount_cents = coupon["discount_value"]
    
        # Clamp each individual unit's post-discount price at 0 cents.
        return max(0, unit_price_cents - discount_cents)
    
    
    def calculate_cart_total(cart: list[dict], coupons: list[dict]) -> int:
        # coupons_by_item: maps item_id -> ordered list of coupon dicts for that item,
        # e.g. {"notebook": [{"coupon_id": "v1", ...}, {"coupon_id": "v3", ...}]}
        coupons_by_item: Dict[str, List[dict]] = {}
        for coupon in coupons:
            item_id = coupon["item_id"]
            if item_id not in coupons_by_item:
                coupons_by_item[item_id] = []
            coupons_by_item[item_id].append(coupon)
    
        # next_coupon_idx: maps item_id -> index of the next unused coupon in coupons_by_item[item_id]
        next_coupon_idx: Dict[str, int] = {}
        total_cents = 0
    
        # Phase 2: price each cart line without looping over individual full-price units.
        for line in cart:
            item_id = line["item_id"]
            unit_price = line["unit_price_cents"]
            quantity = line["quantity"]
    
            item_coupons = coupons_by_item.get(item_id, [])
            start_idx = next_coupon_idx.get(item_id, 0)
            available_coupons = len(item_coupons) - start_idx
    
            # Redeem at most one coupon per unit in list order; surplus coupons are ignored.
            discounted_units = min(quantity, available_coupons)
            for idx in range(start_idx, start_idx + discounted_units):
                total_cents += discounted_unit_price(unit_price, item_coupons[idx])
            next_coupon_idx[item_id] = start_idx + discounted_units
    
            # All remaining units on this line pay full price in one O(1) multiplication.
            full_price_units = quantity - discounted_units
            total_cents += full_price_units * unit_price
    
        return total_cents
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a cashier sorting paper vouchers into labeled trays by product ("notebook", "lamp", ...), keeping each tray's vouchers in the exact order they were scanned. When a shopper buys 100 notebooks and the "notebook" tray holds 2 vouchers, the cashier prices 2 discounted notebooks using those 2 vouchers and totals the remaining 98 notebooks with a single 98 * price multiplication. To prevent penny-rounding bugs on percentage vouchers, we compute raw deductions in exact integer hundredths of a cent (price * percent) and apply banker's rounding (also called round-half-to-even, a rounding rule that sends exact .5 ties to whichever neighboring integer is even so upward and downward biases cancel over large volumes).

Two tempting shortcuts fail in practice. First, expanding every cart line into quantity separate unit objects allocates up to 10^4 * 10^4 = 10^8 entries, timing out even though at most 10^4 vouchers exist. Second, evaluating percentage discounts with binary floating-point numbers (base-2 approximations of decimal fractions) distorts exact half-cent ties: 75 * (14 / 100) becomes 10.500000000000002, tricking round() into returning 11 instead of the even integer 10.

Walk through a tiny cart of 2 lamps at 310 cents each with vouchers [v1: lamp 5% off, v2: mug 40 cents off]:

  • Group vouchers by product: lamp -> [v1], mug -> [v2].
  • Bill lamp (quantity = 2): 1 unit redeems v1. In hundredths of a cent, 310 * 5 = 1550, and divmod(1550, 100) yields quotient 15 and remainder 50 (an exact .50 tie). Because 15 is odd, round-half-to-even rounds up to 16 cents off, charging 310 - 16 = 294 cents.
  • The remaining 2 - 1 = 1 lamp pays full price (1 * 310 = 310 cents), mug is absent from the cart so v2 is skipped, and the final bill is 294 + 310 = 604 cents.

Complexity

  • Time: O(C + M), where C is len(cart) and M is len(coupons). Bucketing vouchers visits all M entries once in O(1) dictionary time per voucher, and billing visits each of the C lines once while advancing through each product's voucher list at most once overall (never iterating over un-discounted quantity).
  • Space: O(M + C) in the worst case (more tightly O(M + U) where U <= C is the count of distinct products), since coupons_by_item stores references to the M vouchers and next_coupon_idx stores one integer cursor per product encountered.

Edge cases

  • Empty cart (cart = []): returns 0 right away, ignoring all supplied vouchers.
  • Empty vouchers (coupons = []): every line sets discounted_units = 0 and adds quantity * unit_price.
  • Exact .50 cent ties going both directions: 290 cents at 5% (14.5 cents) rounds down to even 14, whereas 310 cents at 5% (15.5 cents) rounds up to even 16.
  • Deduction larger than unit price: a 650-cent fixed voucher on a 400-cent cable clamps that single unit to 0 cents (max(0, 400 - 650) = 0) without discounting any other unit.
  • Surplus and unmatched vouchers: extra vouchers past quantity or targeting absent products are ignored cleanly.
  • Large cart totals: 10^4 lines * 10^4 units * 10^6 cents reaches 10^14 cents, overflowing 32-bit signed integers (~2.1 * 10^9) and requiring 64-bit integers in fixed-width languages.

Common mistakes

  • Using floating-point percentages such as price * (value / 100): binary float drift turns exact .5 ties into .500000000000002 or .499999999999996, rounding the wrong way on inputs like 75 at 14% or 45 at 70%.
  • Using round-half-up (hundredths + 50) // 100: always pushes .5 upward (14.5 -> 15), breaking round-half-to-even on every even quotient.
  • Sorting vouchers by largest deduction instead of keeping input order: the specification requires redeeming matching vouchers in scan order ([FIXED 10, FIXED 90] on 1 unit of a 100-cent item yields 90, not 10).
  • Clamping at 0 on the line subtotal instead of per unit: 2 units at 300 cents with one 500-cent voucher must cost 0 + 300 = 300 cents, not max(0, 600 - 500) = 100 cents.
  • Multiplying a "FIXED" voucher by quantity: one voucher only ever discounts one single unit.

Follow-up questions

  • What changes in your data model and calculation rules if shoppers are allowed to combine several coupons onto a single unit? First pin down the exact domain rules because stacking order alters totals: whether vouchers apply in scan order or percentages before fixed deductions, whether subsequent percentages apply to the base unit price or the running subtotal, and whether banker's rounding and the 0-cent floor apply after each voucher or once at the end. In code, each unit's assignment becomes an ordered list of vouchers folded sequentially through discounted_unit_price, and units receiving identical voucher stacks can still be batched so runtime stays independent of raw quantity.
  • Suppose instead of applying coupons in scan order, the checkout engine must assign coupons to minimize the shopper's bill. How would you compute that? When all units of an item_id share the same unit_price_cents, each voucher c produces a fixed cent saving unit_price - discounted_unit_price(unit_price, c) regardless of which unit of that product redeems it. Compute every voucher's saving for item_id and greedily take the min(quantity, len(item_coupons)) largest savings (via heapq.nlargest or sorting in O(M log M) time). If units of the same product could carry different base prices, savings depend on (unit, voucher) pairs, turning assignment into maximum-weight bipartite matching (finding the highest-value one-to-one pairing between two disjoint sets, units and vouchers), solvable via min-cost max-flow or the Hungarian algorithm.
  • How do you guarantee identical cent-level results and a clear audit trail when the same pricing rules run across services written in different languages? Store and compute all currency in integer minor units (cents and integer hundredths of a cent) and forbid binary floating-point types in billing logic, since built-in round helpers differ across runtimes (round(2.5) is 2 in Python, whereas Math.round(2.5) is 3 in Java and JavaScript). Express rounding via explicit integer divmod arithmetic or fixed-point decimals configured with ROUND_HALF_EVEN, verified against a shared language-agnostic test suite covering exact .5 ties, zero floors, and 64-bit totals. For auditability, emit an immutable per-receipt pricing ledger recording the engine version, voucher ID, base cents, raw hundredths, rounded deduction cents, and net cents for every discounted unit.

Follow-up questions

Similar questions

More Palantir interview questions

All 15 Palantir questions →