Maximizing Cart Discounts Within a Point Budget
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Design a cart promotion selector that spends loyalty points to lower a shopper's checkout bill as much as possible. Given a shopping cart items, a catalog of candidate coupons, and an integer point budget (defaulting to 20), implement:
def optimize_coupons(
items: List[Dict],
coupons: List[Dict],
budget: int = 20,
) -> Tuple[int, int, List[str]]:
Input Format
items: A list of product dictionaries, each containing:"id"(str): Distinct product identifier in the cart."category"(str): Department or category tag for the product."price"(int): Pre-discount price in integer cents.
coupons: A list of offer dictionaries, each containing:"id"(str): Distinct offer identifier."level"(str):"ITEM"(applies to one product ID) or"CATEGORY"(applies to every cart product in one category)."target"(str): Target product"id"for"ITEM"offers or target"category"for"CATEGORY"offers (callers may equivalently pass"target_id"or"target_category")."discount_type"(str):"PERCENT"or"FIXED"."value"(int): Integer rate from1to100when"PERCENT", or flat cent deduction per matching product when"FIXED"."max_savings"(int): Maximum combined cents this offer may deduct across the whole cart, or-1when uncapped."cost"(int): Loyalty points needed to enable this offer.
budget: Maximum loyalty points that may be spent across all enabled offers.
Promotion & Stacking Mechanics
- One offer per tier: No product may receive more than one
"ITEM"offer, and no category may have more than one"CATEGORY"offer active at once. - Sequential evaluation: On a product matched by both tiers, evaluate the
"ITEM"offer against the product's starting"price"first; evaluate the"CATEGORY"offer afterward against whatever cent balance remains on that product. - Cent truncation: For
"PERCENT"offers on a current product balanceb, compute the raw deduction per product as(b * value) // 100. For"FIXED"offers, the raw deduction on each matched product isvalue. - Zero-cent floor: A product's remaining balance stops at
0cents and never turns negative. - Offer-wide ceiling: If an offer specifies
max_savings != -1, the sum of cents deducted by that offer across every matched product cannot surpassmax_savings. If a capped"ITEM"offer is clipped bymax_savings, only the clipped deduction is subtracted before the"CATEGORY"pass. - Budget ceiling: The summed
"cost"of enabled offers must satisfytotal_cost <= budget. Enabling zero offers (0cents saved,0points spent,[]) is always legal.
Selection Goal & Tie-Breakers
Choose a legal subset of coupons that yields the largest total cent deduction across the cart:
- If two subsets tie on total cents saved, prefer the subset with the smaller summed point
"cost". - If a tie persists, sort each subset's
"id"strings alphabetically and prefer the list that is lexicographically smaller (element-by-element string comparison from index0).
Return (max_savings_cents, points_spent, sorted_coupon_ids) with sorted_coupon_ids in ascending alphabetical order.
Examples
Example 1
items = [
{"id": "itm_1", "category": "produce", "price": 1200},
{"id": "itm_2", "category": "produce", "price": 600},
]
coupons = [
{"id": "cpn_1", "level": "ITEM", "target": "itm_1", "discount_type": "FIXED", "value": 300, "max_savings": -1, "cost": 6},
{"id": "cpn_2", "level": "CATEGORY", "target": "produce", "discount_type": "PERCENT", "value": 25, "max_savings": 320, "cost": 8},
]
budget = 20
Output: (620, 14, ["cpn_1", "cpn_2"])
Walk-through: Enabling both offers spends 6 + 8 = 14 points (within 20). On itm_1 (1200 cents), cpn_1 deducts 300 cents first, leaving 900 cents; cpn_2 then takes 25% of 900 = 225 cents, leaving 320 - 225 = 95 cents under cpn_2's cap. On itm_2 (600 cents), 25% is 150 cents, which cpn_2's remaining cap clips to 95 cents. Total discount is 300 + 225 + 95 = 620 cents, beating cpn_1 alone (300) and cpn_2 alone (min(320, 300 + 150) = 320).
Example 2
items = [{"id": "itm_9", "category": "snacks", "price": 750}]
coupons = [
{"id": "deal_b", "level": "ITEM", "target": "itm_9", "discount_type": "FIXED", "value": 300, "max_savings": -1, "cost": 7},
{"id": "deal_a", "level": "ITEM", "target": "itm_9", "discount_type": "PERCENT", "value": 40, "max_savings": -1, "cost": 7},
]
budget = 20
Output: (300, 7, ["deal_a"])
Walk-through: Both offers target "itm_9" at the "ITEM" tier, so enabling both at once violates the single-offer-per-tier rule. Individually, deal_b deducts 300 cents for 7 points and deal_a deducts (750 * 40) // 100 = 300 cents for 7 points. Because savings and point cost both tie, ["deal_a"] wins over ["deal_b"] alphabetically.
Constraints
1 <= len(items) <= 501 <= len(coupons) <= 151 <= item["price"] <= 500001 <= coupon["cost"] <= 201 <= coupon["value"] <= 100whendiscount_type == "PERCENT", and1 <= coupon["value"] <= 50000whendiscount_type == "FIXED"coupon["max_savings"] == -1or0 <= coupon["max_savings"] <= 50000budget == 20
Step-by-step walkthrough
Clarify the rules and input keys
We want to choose a valid subset of
couponswhose combined"cost"does not exceedbudget(20loyalty points by default) so total cart savings in cents is as large as possible:- One offer per tier: a product can receive at most one
"ITEM"offer, and each category can have at most one active"CATEGORY"offer. - Sequential two-pass pricing: on any product matched by both tiers, deduct its
"ITEM"offer from the initial"price"first, then evaluate its"CATEGORY"offer against whatever cent balance remains. (A"FIXED"category offer deducts its flat cent amount from each product in that category before enforcing the offer-wide cap.) - Cent truncation & zero floor:
"PERCENT"offers compute(balance * value) // 100per product, and no product's remaining balance can fall below0cents. - Offer-wide ceiling: when
max_savings != -1, the combined cents deducted by that offer across all matched products cannot exceedmax_savings. - Three-tier tie-breaking: higher savings wins; ties prefer lower
points_used; remaining ties prefer the lexicographically smaller alphabetically sorted list of coupon IDs. Choosing no offers(0, 0, [])is always legal. - Target key aliases: coupons normally store the target under
"target", while some callers pass"target_id"or"target_category"; a tiny helper reads whichever key is present.
- One offer per tier: a product can receive at most one
Why subset enumeration beats greedy and simple knapsack
At first glance, spending up to
20points looks like a textbook greedy ("most cents per point") or independent knapsack problem. Both shortcuts break here because offer values depend on which other offers are active:- Enabling an
"ITEM"offer shrinks that product's remaining balance, reducing the cent deduction of a"CATEGORY"percentage offer on the same product. - A
"CATEGORY"offer withmax_savings = 320links every product in that category through one shared cap.
Check the input sizes instead:
len(coupons) <= 15andlen(items) <= 50. The power set (the family of all possible subsets) of15offers contains2^15 = 32,768subsets. Simulating every subset end to end across50products takes roughly32,768 * 50(~1.6million) basic operations — well under a tenth of a second in Python, while handling every interaction accurately.- Enabling an
Represent subsets cleanly with a bitmask
A bitmask encodes a subset of
Noffers as a single integermaskfrom0to2^N - 1((1 << N) - 1), where bitbit_idxis1whencoupons[bit_idx]is enabled and0otherwise:Suppose coupons = [c0, c1, c2] (N = 3, masks 0..7): mask = 5 --> binary 101 | | | +-- bit 0 is 1: include c0 +---- bit 2 is 1: include c2 (bit 1 is 0: skip c1)Checking
(mask >> bit_idx) & 1reads bitbit_idx. We startbest_result = (0, 0, [])formask = 0(enabling zero offers) and iteratemaskfrom1through(1 << num_coupons) - 1, skipping any mask wherepoints_used > budget.Enforce one offer per tier and read targets safely
Given a candidate subset
chosen_coupons, we verify tier exclusivity by indexing offers into two dictionaries:item_coupon_by_id(item_id -> coupon) andcategory_coupon_by_cat(category -> coupon). Whenever two selected offers collide on the same key in either dictionary, they would illegally stack at the same tier, so_evaluate_subsetreturnsNoneimmediately.from typing import Dict def _get_target(coupon: Dict) -> str: """Return the item ID (for ITEM level) or category name (for CATEGORY level).""" # Accept "target" as well as the "target_id" / "target_category" key aliases. if "target" in coupon: return coupon["target"] if coupon["level"] == "ITEM": return coupon["target_id"] return coupon["target_category"]Price products in two stages with a shared cap allowance
Next we simulate the two-pass checkout pipeline across
items:Product balance pipeline: item["price"] ---> [ ITEM offer (if any) ] ---> remaining_price ---> [ CATEGORY offer (if any) ] - floor % or fixed - floor % or fixed - clipped to price - clipped to remaining_price - clipped to remaining_cap - clipped to remaining_capTo enforce
max_savingsacross multiple products cleanly, treatmax_savingslike a prepaid gift-card allowance (remaining_cap[coupon_id]) initialized before looping over the cart:- Whenever a capped offer would deduct
discountcents on a product, clampdiscount = min(discount, remaining_cap[coupon_id])and subtractdiscountfromremaining_cap[coupon_id]. - Summed across every product in a category, the offer grants
min(max_savings, sum of per-product discounts)regardless of cart order, and a capped"ITEM"offer reducesremaining_priceonly by the actual capped deduction.
from typing import Dict, List, Optional def _raw_item_discount(balance: int, coupon: Dict) -> int: """Compute one coupon's discount on a single item balance, floored at 0 remaining price.""" if coupon["discount_type"] == "PERCENT": # Truncate percentage discounts down to whole cents via integer division. discount = (balance * coupon["value"]) // 100 else: discount = coupon["value"] # Clamp so an item's remaining balance never drops below 0 cents. return min(discount, balance) def _evaluate_subset(items: List[Dict], chosen_coupons: List[Dict]) -> Optional[int]: """Return total savings in cents for `chosen_coupons`, or None if two coupons stack illegally.""" item_coupon_by_id: Dict[str, Dict] = {} category_coupon_by_cat: Dict[str, Dict] = {} for coupon in chosen_coupons: target = _get_target(coupon) if coupon["level"] == "ITEM": if target in item_coupon_by_id: return None item_coupon_by_id[target] = coupon else: if target in category_coupon_by_cat: return None category_coupon_by_cat[target] = coupon remaining_cap: Dict[str, int] = {} for coupon in chosen_coupons: if coupon["max_savings"] != -1: remaining_cap[coupon["id"]] = coupon["max_savings"] total_savings = 0 for item in items: remaining_price = item["price"] item_coupon = item_coupon_by_id.get(item["id"]) if item_coupon is not None: discount = _raw_item_discount(remaining_price, item_coupon) coupon_id = item_coupon["id"] if coupon_id in remaining_cap: discount = min(discount, remaining_cap[coupon_id]) remaining_cap[coupon_id] -= discount remaining_price -= discount total_savings += discount cat_coupon = category_coupon_by_cat.get(item["category"]) if cat_coupon is not None: discount = _raw_item_discount(remaining_price, cat_coupon) coupon_id = cat_coupon["id"] if coupon_id in remaining_cap: discount = min(discount, remaining_cap[coupon_id]) remaining_cap[coupon_id] -= discount total_savings += discount return total_savings- Whenever a capped offer would deduct
Compare candidates with three-tier tie-breaking
For every valid subset within
budget, we rank(savings, points_used, sorted_ids)in order:- Higher
savingswins (cand_savings > best_savings). - On equal
savings, lowerpoints_usedwins (cand_cost < best_cost). - On equal
savingsandpoints_used, the lexicographically smaller sorted ID list wins (cand_ids < best_ids). Lexicographical order compares two lists item by item from index0like dictionary words:["a", "z"] < ["b"]isTruebecause"a" < "b"at index0, even though["a", "z"]has two elements.
from typing import List, Tuple def _is_better_choice( candidate: Tuple[int, int, List[str]], best: Tuple[int, int, List[str]], ) -> bool: """Return True if `candidate` beats `best` on savings, then lower cost, then sorted IDs.""" cand_savings, cand_cost, cand_ids = candidate best_savings, best_cost, best_ids = best if cand_savings != best_savings: return cand_savings > best_savings if cand_cost != best_cost: return cand_cost < best_cost return cand_ids < best_ids- Higher
Trace Example 1 and Example 2
Example 1: items: itm_1 (produce, 1200), itm_2 (produce, 600) coupons: cpn_1 (ITEM itm_1, FIXED 300, uncapped, cost 6) cpn_2 (CATEGORY produce, PERCENT 25, cap 320, cost 8) mask 00 -> {}: savings = 0, points = 0, ids = [] mask 01 -> {cpn_1}: itm_1 gets 300 off -> savings = 300, points = 6, ids = ["cpn_1"] mask 10 -> {cpn_2}: itm_1: 25% of 1200 = 300 (cap 320 -> 20 left) itm_2: 25% of 600 = 150, clipped to remaining cap 20! savings = 300 + 20 = 320, points = 8, ids = ["cpn_2"] mask 11 -> {cpn_1, cpn_2}: itm_1: cpn_1 deducts 300 (balance 900); cpn_2 deducts 25% of 900 = 225 (cap 320 -> 95) itm_2: cpn_2 raw 25% of 600 = 150, clipped to remaining cap 95! savings = 300 + 225 + 95 = 620, points = 14, ids = ["cpn_1", "cpn_2"] Winner: (620, 14, ["cpn_1", "cpn_2"]) Example 2: items: itm_9 (snacks, 750) coupons: deal_b (ITEM itm_9, FIXED 300, cost 7), deal_a (ITEM itm_9, PERCENT 40, cost 7) mask 01 -> {deal_b}: saves 300, points = 7, ids = ["deal_b"] mask 10 -> {deal_a}: saves 300, points = 7, ids = ["deal_a"] mask 11 -> {deal_b, deal_a}: rejected (two ITEM offers target "itm_9") Tie-break on (300, 7): ["deal_a"] < ["deal_b"] --> Winner: (300, 7, ["deal_a"])Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def _get_target(coupon: Dict) -> str: """Return the item ID (for ITEM level) or category name (for CATEGORY level).""" # Accept "target" as well as the "target_id" / "target_category" key aliases. if "target" in coupon: return coupon["target"] if coupon["level"] == "ITEM": return coupon["target_id"] return coupon["target_category"] def _raw_item_discount(balance: int, coupon: Dict) -> int: """Compute one coupon's discount on a single item balance, floored at 0 remaining price.""" if coupon["discount_type"] == "PERCENT": # Truncate percentage discounts down to whole cents via integer division. discount = (balance * coupon["value"]) // 100 else: discount = coupon["value"] # Clamp so an item's remaining balance never drops below 0 cents. return min(discount, balance) def _evaluate_subset(items: List[Dict], chosen_coupons: List[Dict]) -> Optional[int]: """Return total savings in cents for `chosen_coupons`, or None if two coupons stack illegally.""" # item_coupon_by_id: maps item_id -> single active ITEM coupon dict, e.g. {"itm_1": {...}} item_coupon_by_id: Dict[str, Dict] = {} # category_coupon_by_cat: maps category -> single active CATEGORY coupon dict, e.g. {"produce": {...}} category_coupon_by_cat: Dict[str, Dict] = {} # Reject any subset that places two offers on the same item ID or the same category. for coupon in chosen_coupons: target = _get_target(coupon) if coupon["level"] == "ITEM": if target in item_coupon_by_id: return None item_coupon_by_id[target] = coupon else: if target in category_coupon_by_cat: return None category_coupon_by_cat[target] = coupon # remaining_cap: maps coupon_id -> cents of savings still allowed before hitting max_savings # (think of max_savings as a shared gift-card allowance across every item that coupon touches). remaining_cap: Dict[str, int] = {} for coupon in chosen_coupons: if coupon["max_savings"] != -1: remaining_cap[coupon["id"]] = coupon["max_savings"] # Rules 2 & 5: apply ITEM coupon first to original price, then CATEGORY coupon to remaining balance. total_savings = 0 for item in items: remaining_price = item["price"] item_coupon = item_coupon_by_id.get(item["id"]) if item_coupon is not None: discount = _raw_item_discount(remaining_price, item_coupon) coupon_id = item_coupon["id"] if coupon_id in remaining_cap: discount = min(discount, remaining_cap[coupon_id]) remaining_cap[coupon_id] -= discount remaining_price -= discount total_savings += discount cat_coupon = category_coupon_by_cat.get(item["category"]) if cat_coupon is not None: discount = _raw_item_discount(remaining_price, cat_coupon) coupon_id = cat_coupon["id"] if coupon_id in remaining_cap: discount = min(discount, remaining_cap[coupon_id]) remaining_cap[coupon_id] -= discount total_savings += discount return total_savings def _is_better_choice( candidate: Tuple[int, int, List[str]], best: Tuple[int, int, List[str]], ) -> bool: """Return True if `candidate` beats `best` on savings, then lower cost, then sorted IDs.""" cand_savings, cand_cost, cand_ids = candidate best_savings, best_cost, best_ids = best if cand_savings != best_savings: return cand_savings > best_savings if cand_cost != best_cost: return cand_cost < best_cost # Both ID lists are sorted alphabetically; Python compares lists element by element. return cand_ids < best_ids def optimize_coupons( items: List[Dict], coupons: List[Dict], budget: int = 20, ) -> Tuple[int, int, List[str]]: num_coupons = len(coupons) # Default to activating no coupons: 0 cents saved, 0 points spent, empty ID list. best_result: Tuple[int, int, List[str]] = (0, 0, []) # Enumerate every non-empty subset via a bitmask from 1 to 2^num_coupons - 1 (at most 32,767). for mask in range(1, 1 << num_coupons): chosen_coupons: List[Dict] = [] points_used = 0 for bit_idx in range(num_coupons): if (mask >> bit_idx) & 1: coupon = coupons[bit_idx] chosen_coupons.append(coupon) points_used += coupon["cost"] # Rule 6: total point cost of activated coupons cannot exceed budget (<= allows exact match). if points_used > budget: continue savings = _evaluate_subset(items, chosen_coupons) if savings is None: continue sorted_ids = sorted(coupon["id"] for coupon in chosen_coupons) candidate = (savings, points_used, sorted_ids) if _is_better_choice(candidate, best_result): best_result = candidate return best_result✅ Submit now — all tests should pass.
Intuition & how it works
With at most 15 offers in coupons, the entire power set (the family of all 2^N possible subsets of N offers) has at most 2^15 = 32,768 candidates. Rather than guessing how offers will alter each other's payouts in advance, we encode each subset as a bitmask (an integer whose binary 0/1 bits indicate which offers are off or on), discard subsets that exceed budget or collide on the same tier target, and run the exact two-pass checkout calculation over items. For any offer with a ceiling max_savings != -1, we maintain remaining_cap like a shared prepaid gift-card balance across every product it touches: each product draws up to the remaining allowance until that ceiling reaches 0.
Why do greedy rules ("pick highest cents saved per point") or plain independent knapsack DP fail? Even without interactions, a 20-point limit is a 0/1 knapsack constraint (each offer is taken whole or left behind), so one 11-point offer saving 500 cents can crowd out two 10-point offers saving 300 + 300 = 600 cents. On top of that, offers directly reshape one another's value: deducting an "ITEM" offer lowers the balance multiplied by a "CATEGORY" percentage offer, while max_savings couples multiple products in the same category.
Walk through Example 1's produce cart (itm_1 at 1200 cents, itm_2 at 600 cents) with cpn_1 (300 cents off itm_1, 6 points) and cpn_2 (25% off "produce" capped at 320 cents, 8 points):
- Subset
{cpn_1}(6points):cpn_1deducts300cents fromitm_1. - Subset
{cpn_2}(8points):25%of1200(300) plus25%of600(150) is450cents, whichcpn_2's shared allowance clips to320cents. - Subset
{cpn_1, cpn_2}(14points, within20): onitm_1,cpn_1deducts300cents first (leaving900), thencpn_2deducts25%of900 = 225cents (loweringcpn_2's320-cent cap to95); onitm_2,cpn_2's raw25%of600 = 150is clipped to the remaining95cap, yielding300 + 225 + 95 = 620cents saved for14points — the winning result(620, 14, ["cpn_1", "cpn_2"]).
Complexity
Let N be len(coupons) (<= 15) and M be len(items) (<= 50):
- Time: O(2^N * (N log N + M)). We inspect
2^N - 1non-empty bitmasks; for each mask withinbudget, decoding bits and building the target/cap lookup dicts takesO(N)work, running the two-pass pricing loop visits allMproducts once inO(M)work, and sorting selected offer IDs for tie-breaking takesO(N log N)work. AtN = 15, M = 50, that totals roughly two million fast integer operations. - Space: O(N) auxiliary memory, held by
chosen_coupons, the conflict andremaining_capdictionaries (at mostNentries each), and the sorted ID lists of the current and best subsets.
Edge cases
- Zero helpful offers (every offer targets absent products/categories, exceeds
budget, or hasmax_savings = 0): every non-empty subset either saves0at cost>= 1or is skipped, so the baseline(0, 0, [])wins on lower point cost. - Deduction larger than product price: an
800-cent"FIXED""ITEM"offer on a500-cent product clamps to500cents (remaining_price = 0), leaving0extra savings for any"CATEGORY"offer on that product — so omitting the redundant category offer wins on lower point cost. - Per-product integer truncation:
(balance * value) // 100floors each product individually (15%of999is149, leaving850, and33%of850is280). - Capped
"ITEM"offer feeding"CATEGORY"offer: if a50%"ITEM"offer on1000cents hasmax_savings = 100,remaining_pricedrops to900(not500), so a10%"CATEGORY"offer deducts90cents. - Alphabetical list tie-break vs. subset cardinality: lexicographical order compares sorted lists element by element from index
0, so["a", "z"]beats["b"]when savings and points match because"a" < "b". - Target key aliases:
_get_targethandles"target"as well as"target_id"/"target_category"cleanly.
Common mistakes
- Enforcing
max_savingsper product rather than across the entire offer: a"CATEGORY"offer withmax_savings = 250that deducts100cents on each of3products must savemin(250, 300) = 250cents overall, notmin(250, 100) * 3 = 300cents. - Applying
"CATEGORY"offers to the initialitem["price"]: the"ITEM"pass must run first so"CATEGORY"percentages multiply the reducedremaining_price. - Adding category balances together before truncating percentages:
(850 * 33) // 100 + (999 * 33) // 100 = 280 + 329 = 609, whereas truncating the combined1849balance gives610(off by1cent). - Floating-point rounding
int(balance * (value / 100)): binary float imprecision turnsint(100 * (29 / 100))into28instead of29; stick to exact integer(balance * value) // 100. - Returning unsorted coupon IDs or comparing ID lists before sorting them.
Alternative approaches
- Branch-and-bound backtracking: build subsets recursively one offer at a time, pruning immediately whenever
points_used > budgetor a(level, target)slot is already occupied. When many offers share targets or carry high point costs, pruning skips most of the2^Nsearch tree while preserving exact optimality.
Follow-up questions
- Suppose up to 100 coupons are available, and coupons belonging to distinct product categories never interact—how can you find the optimal subset without enumerating 2^100 combinations? Group products and offers by
categoryso each category becomes a self-contained subproblem (its"CATEGORY"offers plus"ITEM"offers targeting products in that category). Inside one category, at most one"CATEGORY"offer can be active, so try each option (none, or one specific"CATEGORY"offer) and run dynamic programming (DP) (solving overlapping subproblems once and caching optimal sub-results in a table) across that category's products for point budgets0..20— adding the used cap (0..max_savings) to the DP state whenever the chosen category offer is capped. Once every category produces its best savings curve over0..20points, combine categories via a20-point grouped knapsack DP inO(G * budget^2)time forGcategories; to preserve exact lexicographical tie-breaking, reconstruct choices in alphabetical ID order after locking in the optimal(savings, points_used). - If an item could accept an arbitrary number of stacked category coupons, what dynamic programming state would compute the lowest achievable final price for one item? Once multiple offers stack on one product, order matters (on a
1000-cent product,100off then50%off leaves450, whereas50%off then100off leaves400). ForKoffers applicable to one product, define a subset-DP tablemin_balance[mask]holding the smallest remaining cent balance after applying the exact subsetmaskin the best permutation, starting frommin_balance[0] = item["price"]and relaxingmin_balance[mask | (1 << j)] = min(..., balance_after(coupon_j, min_balance[mask]))inO(2^K * K)time. Storing only the single minimum balance permaskis sound because both integer-floor percentage deductions (<= 100%) and fixed deductions are monotonically non-decreasing functions of the input balance (though sharedmax_savingsceilings across multiple products still require tracking cap usage across products). - How would you extend the checkout pipeline to support cart-wide threshold promotions (such as a flat cent discount when the cart total reaches a minimum spend) alongside item and category offers? Append a third pass after all product and category deductions complete: sum the post-category
remaining_priceacross all products to obtain the cart subtotal, check whether that subtotal satisfies the order offer's spend threshold (confirming with product specs whether qualification uses pre-discount or post-discount subtotal), and deduct the cart-wide offer floored at0and bounded bymax_savings. Notice that post-discount thresholds introduce non-monotonic behavior — enabling an item offer might drop the subtotal from5050to4950and forfeit a1000-cent cart promotion — which full subset simulation handles cleanly because each candidate subset runs through all three passes.
Follow-up questions
- Suppose up to 100 coupons are available, and coupons belonging to distinct product categories never interact—how can you find the optimal subset without enumerating 2^100 combinations?
- If an item could accept an arbitrary number of stacked category coupons, what dynamic programming state would compute the lowest achievable final price for one item?
- How would you extend the checkout pipeline to support cart-wide threshold promotions (such as a flat cent discount when the cart total reaches a minimum spend) alongside item and category offers?
Similar questions
- Cart Checkout Pricing with Half-to-Even Unit Vouchers
- Isolated Multi-Tenant Analytics Engine with ABAC and Audit Compliance
- Design a Low-Latency Airspace Conflict Detector for Drone Operations
- Scalable Interview Question Repository and Live Selection System
- Design a Pull-Based Fleet Metrics Collector
- Design a Governed Tool Catalog and Execution Gateway for AI Agents
More Palantir interview questions
- Cart Checkout Pricing with Half-to-Even Unit Vouchers 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