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 from 1 to 100 when "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 -1 when 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

  1. 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.
  2. 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.
  3. Cent truncation: For "PERCENT" offers on a current product balance b, compute the raw deduction per product as (b * value) // 100. For "FIXED" offers, the raw deduction on each matched product is value.
  4. Zero-cent floor: A product's remaining balance stops at 0 cents and never turns negative.
  5. Offer-wide ceiling: If an offer specifies max_savings != -1, the sum of cents deducted by that offer across every matched product cannot surpass max_savings. If a capped "ITEM" offer is clipped by max_savings, only the clipped deduction is subtracted before the "CATEGORY" pass.
  6. Budget ceiling: The summed "cost" of enabled offers must satisfy total_cost <= budget. Enabling zero offers (0 cents saved, 0 points spent, []) is always legal.

Selection Goal & Tie-Breakers

Choose a legal subset of coupons that yields the largest total cent deduction across the cart:

  1. If two subsets tie on total cents saved, prefer the subset with the smaller summed point "cost".
  2. 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 index 0).

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) <= 50
  • 1 <= len(coupons) <= 15
  • 1 <= item["price"] <= 50000
  • 1 <= coupon["cost"] <= 20
  • 1 <= coupon["value"] <= 100 when discount_type == "PERCENT", and 1 <= coupon["value"] <= 50000 when discount_type == "FIXED"
  • coupon["max_savings"] == -1 or 0 <= coupon["max_savings"] <= 50000
  • budget == 20

Step-by-step walkthrough

  1. Clarify the rules and input keys

    We want to choose a valid subset of coupons whose combined "cost" does not exceed budget (20 loyalty 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) // 100 per product, and no product's remaining balance can fall below 0 cents.
    • Offer-wide ceiling: when max_savings != -1, the combined cents deducted by that offer across all matched products cannot exceed max_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.
  2. Why subset enumeration beats greedy and simple knapsack

    At first glance, spending up to 20 points 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 with max_savings = 320 links every product in that category through one shared cap.

    Check the input sizes instead: len(coupons) <= 15 and len(items) <= 50. The power set (the family of all possible subsets) of 15 offers contains 2^15 = 32,768 subsets. Simulating every subset end to end across 50 products takes roughly 32,768 * 50 (~1.6 million) basic operations — well under a tenth of a second in Python, while handling every interaction accurately.

  3. Represent subsets cleanly with a bitmask

    A bitmask encodes a subset of N offers as a single integer mask from 0 to 2^N - 1 ((1 << N) - 1), where bit bit_idx is 1 when coupons[bit_idx] is enabled and 0 otherwise:

    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) & 1 reads bit bit_idx. We start best_result = (0, 0, []) for mask = 0 (enabling zero offers) and iterate mask from 1 through (1 << num_coupons) - 1, skipping any mask where points_used > budget.

  4. 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) and category_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_subset returns None immediately.

    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"]
    
  5. 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_cap
    

    To enforce max_savings across multiple products cleanly, treat max_savings like a prepaid gift-card allowance (remaining_cap[coupon_id]) initialized before looping over the cart:

    • Whenever a capped offer would deduct discount cents on a product, clamp discount = min(discount, remaining_cap[coupon_id]) and subtract discount from remaining_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 reduces remaining_price only 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
    
  6. Compare candidates with three-tier tie-breaking

    For every valid subset within budget, we rank (savings, points_used, sorted_ids) in order:

    1. Higher savings wins (cand_savings > best_savings).
    2. On equal savings, lower points_used wins (cand_cost < best_cost).
    3. On equal savings and points_used, the lexicographically smaller sorted ID list wins (cand_ids < best_ids). Lexicographical order compares two lists item by item from index 0 like dictionary words: ["a", "z"] < ["b"] is True because "a" < "b" at index 0, 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
    
  7. 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"])
    
  8. 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} (6 points): cpn_1 deducts 300 cents from itm_1.
  • Subset {cpn_2} (8 points): 25% of 1200 (300) plus 25% of 600 (150) is 450 cents, which cpn_2's shared allowance clips to 320 cents.
  • Subset {cpn_1, cpn_2} (14 points, within 20): on itm_1, cpn_1 deducts 300 cents first (leaving 900), then cpn_2 deducts 25% of 900 = 225 cents (lowering cpn_2's 320-cent cap to 95); on itm_2, cpn_2's raw 25% of 600 = 150 is clipped to the remaining 95 cap, yielding 300 + 225 + 95 = 620 cents saved for 14 points — 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 - 1 non-empty bitmasks; for each mask within budget, decoding bits and building the target/cap lookup dicts takes O(N) work, running the two-pass pricing loop visits all M products once in O(M) work, and sorting selected offer IDs for tie-breaking takes O(N log N) work. At N = 15, M = 50, that totals roughly two million fast integer operations.
  • Space: O(N) auxiliary memory, held by chosen_coupons, the conflict and remaining_cap dictionaries (at most N entries 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 has max_savings = 0): every non-empty subset either saves 0 at cost >= 1 or is skipped, so the baseline (0, 0, []) wins on lower point cost.
  • Deduction larger than product price: an 800-cent "FIXED" "ITEM" offer on a 500-cent product clamps to 500 cents (remaining_price = 0), leaving 0 extra 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) // 100 floors each product individually (15% of 999 is 149, leaving 850, and 33% of 850 is 280).
  • Capped "ITEM" offer feeding "CATEGORY" offer: if a 50% "ITEM" offer on 1000 cents has max_savings = 100, remaining_price drops to 900 (not 500), so a 10% "CATEGORY" offer deducts 90 cents.
  • 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_target handles "target" as well as "target_id" / "target_category" cleanly.

Common mistakes

  • Enforcing max_savings per product rather than across the entire offer: a "CATEGORY" offer with max_savings = 250 that deducts 100 cents on each of 3 products must save min(250, 300) = 250 cents overall, not min(250, 100) * 3 = 300 cents.
  • Applying "CATEGORY" offers to the initial item["price"]: the "ITEM" pass must run first so "CATEGORY" percentages multiply the reduced remaining_price.
  • Adding category balances together before truncating percentages: (850 * 33) // 100 + (999 * 33) // 100 = 280 + 329 = 609, whereas truncating the combined 1849 balance gives 610 (off by 1 cent).
  • Floating-point rounding int(balance * (value / 100)): binary float imprecision turns int(100 * (29 / 100)) into 28 instead of 29; 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 > budget or a (level, target) slot is already occupied. When many offers share targets or carry high point costs, pruning skips most of the 2^N search 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 category so 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 budgets 0..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 over 0..20 points, combine categories via a 20-point grouped knapsack DP in O(G * budget^2) time for G categories; 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, 100 off then 50% off leaves 450, whereas 50% off then 100 off leaves 400). For K offers applicable to one product, define a subset-DP table min_balance[mask] holding the smallest remaining cent balance after applying the exact subset mask in the best permutation, starting from min_balance[0] = item["price"] and relaxing min_balance[mask | (1 << j)] = min(..., balance_after(coupon_j, min_balance[mask])) in O(2^K * K) time. Storing only the single minimum balance per mask is sound because both integer-floor percentage deductions (<= 100%) and fixed deductions are monotonically non-decreasing functions of the input balance (though shared max_savings ceilings 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_price across 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 at 0 and bounded by max_savings. Notice that post-discount thresholds introduce non-monotonic behavior — enabling an item offer might drop the subtotal from 5050 to 4950 and forfeit a 1000-cent cart promotion — which full subset simulation handles cleanly because each candidate subset runs through all three passes.

Follow-up questions

Similar questions

More Palantir interview questions

All 15 Palantir questions →