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
- 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; whenquantityexceeds the count of matching vouchers, the remaining units are billed atunit_price_cents. - Unused vouchers: Vouchers targeting an
item_idabsent fromcart, as well as extra vouchers left over once every unit of thatitem_idalready has a voucher, are ignored. - 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. - Banker's rounding on percentages: When
discount_type == "PERCENT", compute the exact cent deduction(unit_price_cents * discount_value) / 100and round fractional cents to the closest integer using round-half-to-even: if the fraction is.5on the nose, round toward whichever adjacent integer is even (for instance,14.5rounds to14, while15.5rounds to16). - Sequential voucher priority: When multiple vouchers target the same
item_id, redeem them in the exact order they appear incoupons.
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 incart, so it is skipped. - Unit 1 of
"notebook"gets5%off290cents:290 * 5 / 100 = 14.5cents, which rounds half-to-even to14cents, leaving290 - 14 = 276cents. - Unit 2 of
"notebook"pays full price (290cents), and"pen"costs120cents, totaling276 + 290 + 120 = 686cents.
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^40 <= len(coupons) <= 10^41 <= unit_price_cents <= 10^61 <= quantity <= 10^41 <= discount_value <= 100whendiscount_type == "PERCENT"1 <= discount_value <= 10^6whendiscount_type == "FIXED"
Step-by-step walkthrough
Understand the billing rules
Given
cartlines (item_id,unit_price_cents,quantity) andcoupons(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 incoupons. - Skip unmatched or surplus vouchers: vouchers targeting products absent from
cart, or vouchers left over pastquantity, 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) / 100rounded to the closest cent with round-half-to-even (exact.5ties pick the even integer neighbor:14.5 -> 14,15.5 -> 16).
- One voucher per unit, in list order: each voucher applies to at most one unit of its
Why expanding every unit is too slow
A literal unit-by-unit simulation creates one record per physical item unit, scans
couponsattaching each voucher to the first un-discounted unit of that product, and sums the unit charges.While fine on tiny carts,
len(cart)can reach10^4and each line'squantitycan also reach10^4. Materializing10^4 * 10^4 = 10^8unit records blows through memory and time limits in Python. Yetlen(coupons) <= 10^4: out of10^8units, at most10,000ever receive a discount!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:- Bucket
couponsinto a dictionarycoupons_by_item[item_id]preserving input order. Each list acts like a queue of vouchers waiting for units of that product. - When billing a cart line with
quantityunits, consumediscounted_units = min(quantity, available_coupons)vouchers from that product's queue and price those units one by one. - Bill all remaining
quantity - discounted_unitsfull-price units in oneO(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 incoupons_by_item[item_id]) also handles carts where the sameitem_idappears across multiple lines without ever double-spending a voucher.- Bucket
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 like0.14or0.70exactly: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_centsanddiscount_valueare integers,hundredths_of_cent = unit_price_cents * discount_valueis exact. Splitting by100viaquotient, 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 the0-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)Match vouchers to cart lines in list order
Next, bucket vouchers by
item_id, step throughcart, redeemdiscounted_unitsvouchers 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_centsVouchers whose
item_idnever occurs incartstay untouched incoupons_by_item.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 = 590Complete 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):1unit redeemsv1. In hundredths of a cent,310 * 5 = 1550, anddivmod(1550, 100)yields quotient15and remainder50(an exact.50tie). Because15is odd, round-half-to-even rounds up to16cents off, charging310 - 16 = 294cents. - The remaining
2 - 1 = 1lamp pays full price (1 * 310 = 310cents),mugis absent from the cart sov2is skipped, and the final bill is294 + 310 = 604cents.
Complexity
- Time: O(C + M), where
Cislen(cart)andMislen(coupons). Bucketing vouchers visits allMentries once in O(1) dictionary time per voucher, and billing visits each of theClines once while advancing through each product's voucher list at most once overall (never iterating over un-discountedquantity). - Space: O(M + C) in the worst case (more tightly
O(M + U)whereU <= Cis the count of distinct products), sincecoupons_by_itemstores references to theMvouchers andnext_coupon_idxstores one integer cursor per product encountered.
Edge cases
- Empty cart (
cart = []): returns0right away, ignoring all supplied vouchers. - Empty vouchers (
coupons = []): every line setsdiscounted_units = 0and addsquantity * unit_price. - Exact
.50cent ties going both directions:290cents at5%(14.5cents) rounds down to even14, whereas310cents at5%(15.5cents) rounds up to even16. - Deduction larger than unit price: a
650-cent fixed voucher on a400-cent cable clamps that single unit to0cents (max(0, 400 - 650) = 0) without discounting any other unit. - Surplus and unmatched vouchers: extra vouchers past
quantityor targeting absent products are ignored cleanly. - Large cart totals:
10^4lines *10^4units *10^6cents reaches10^14cents, 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.5ties into.500000000000002or.499999999999996, rounding the wrong way on inputs like75at14%or45at70%. - Using round-half-up
(hundredths + 50) // 100: always pushes.5upward (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]on1unit of a100-cent item yields90, not10). - Clamping at
0on the line subtotal instead of per unit:2units at300cents with one500-cent voucher must cost0 + 300 = 300cents, notmax(0, 600 - 500) = 100cents. - Multiplying a
"FIXED"voucher byquantity: 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 throughdiscounted_unit_price, and units receiving identical voucher stacks can still be batched so runtime stays independent of rawquantity. - 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_idshare the sameunit_price_cents, each vouchercproduces a fixed cent savingunit_price - discounted_unit_price(unit_price, c)regardless of which unit of that product redeems it. Compute every voucher's saving foritem_idand greedily take themin(quantity, len(item_coupons))largest savings (viaheapq.nlargestor sorting inO(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
roundhelpers differ across runtimes (round(2.5)is2in Python, whereasMath.round(2.5)is3in Java and JavaScript). Express rounding via explicit integerdivmodarithmetic or fixed-point decimals configured withROUND_HALF_EVEN, verified against a shared language-agnostic test suite covering exact.5ties, 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
- What changes in your data model and calculation rules if shoppers are allowed to combine several coupons onto a single unit?
- 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?
- 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?
Similar questions
- Shortest Hops and Distance on Two-Way Roads
- Inverted Interest Index and Shared Employee Pairs
- Combine K Sorted Lists via Divide and Conquer
- Grid Snake Simulation with Per-Move Scores
- Checkout Total Under Capped Multiplicative Coupons
- Isolated Multi-Tenant Analytics Engine with ABAC and Audit Compliance
More Palantir interview questions
- Maximizing Cart Discounts Within a Point Budget Medium
- Design a Low-Latency Airspace Conflict Detector for Drone Operations Medium
- Design a Pull-Based Fleet Metrics Collector Easy Pro
- Design a Governed Tool Catalog and Execution Gateway for AI Agents Medium Pro
- Shortest Hops and Distance on Two-Way Roads Easy Pro
- Inverted Interest Index and Shared Employee Pairs Medium Pro
- Grid Snake Simulation with Per-Move Scores Medium Pro
- Checkout Total Under Capped Multiplicative Coupons Medium Pro
- Isolated Multi-Tenant Analytics Engine with ABAC and Audit Compliance Medium Pro
- Scalable Interview Question Repository and Live Selection System Hard Pro