Cheapest Cart Total with Percent-Off and Buy-X-Get-Y Promotions
Math & Bit ManipulationModel answerLast updated
Define pricing rules for percent-off and buy-X-get-Y promotions, then build an algorithm that returns the lowest legal total for a cart, covering stacking, repeats, and rounding.
You are asked to build a pricing routine for a checkout system. The input is a list of purchased line items (product, unit price, quantity) and a set of promotions. The routine must return the lowest total the customer is allowed to pay.
Two kinds of promotions exist:
- Percentage promotions: take a given percentage off an eligible amount.
- Buy-X-get-Y promotions: when a customer buys X units of an eligible product, Y additional units are free.
The problem deliberately leaves many rules open. The schema of the records, which items a promotion applies to, whether promotions can be combined, how often one can be applied, which items become free when prices differ, and when rounding occurs are all unspecified.
What is expected:
- List the clarifying questions you would ask and state the assumptions you choose for each one. You should not claim a single "lowest price" until these are settled.
- Describe a data model for the cart and for the promotions.
- Give an algorithm that, under your stated assumptions, really does find the minimum price (not just a plausible price).
- Explain how you handle quantity thresholds, interactions between promotions, and rounding.
- Describe how you would test the result for correctness and reproducibility.
Code is welcome but not required. A precise, well-justified procedure matters more than a particular language.
Hints
Hint 1
Before designing anything, pin down semantics: does 'buy X get Y' mean X paid plus Y free per group of X+Y units, can it repeat, and which units are the free ones when prices differ?
Hint 2
Separate the problem into eligibility (which promotions can touch which units) and evaluation (what each valid combination costs). If stacking is allowed, the order of percent-off versus free-unit promotions changes the result, so you must either fix an order or search over orders.
Hint 3
If promotions cannot stack and each product line is independent, the optimum is simply the minimum over the options per line. If they can stack across shared units, think about enumerating a small set of candidate plans, or a greedy rule you can justify with an exchange argument. Use integer minor units (cents) and round at one defined step.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first, then commit to assumptions
The phrase "lowest price" is only well defined once the rules are fixed. The questions I would ask, and the defaults I would choose if the interviewer lets me decide:
| Question | Assumption I would state |
|---|---|
| What does buy X get Y mean? | Each complete group of X+Y units of an eligible product has X paid units and Y free units. It repeats: floor(qty / (X+Y)) groups. |
| Which units are free when prices differ? | The cheapest units within the eligible set become free. This is the customer-favorable reading and is the usual one. |
| Do promotions stack? | A single unit may receive at most one promotion (no stacking on the same unit). Different units of the cart can use different promotions. |
| Scope of a percentage promotion? | Applies to a product, a category, or the whole cart, as declared by the promotion. |
| Is the best choice per line, per product, or per cart? | Per cart overall, because a promotion with cart-wide scope competes with line-level ones. |
| Usage limits? | Each promotion has an optional maximum number of applications per transaction. |
| Rounding? | All money is stored as integer cents. Round once, half-up, at the end of each promotion's computation (or, alternatively, once per line). The choice is fixed and documented. |
Without these, two correct implementations can legitimately return different numbers. That is the main point of the exercise.
2. Data model
Item:sku,unit_price_cents,qty.PercentPromo:id,percent(0 to 100),scope(set of SKUs or "all"),max_uses.BuyGetPromo:id,x,y,scope(SKUs),max_uses.
Expand or group the cart into a multiset of units, which is cheap because only price and SKU matter.
3. Algorithm under the "one promotion per unit" assumption
Case A: independent product lines, no cart-wide promotions. For each SKU, compute the cost under every applicable promotion and under no promotion, then take the minimum.
- Percent promo:
qty * price * (100 - p) / 100, rounded once. - Buy-X-get-Y:
groups = min(qty // (x+y), max_uses), free units =groups * y, cost =(qty - free) * price.
Sum the minimum per SKU.
Case B: promotions share units (cross-SKU scopes or cart-wide percentage). Now it is an assignment problem: each unit is assigned to at most one promotion, subject to group-size and usage limits.
Practical approach:
- For buy-X-get-Y promotions with a shared scope, sort eligible units by price descending. Within each group of X+Y units, the free ones are the Y cheapest. Taking the groups from the sorted list (most expensive units first fill the paid slots) maximizes savings: this is justified by an exchange argument, since swapping a cheaper free unit with a more expensive paid unit never reduces the saving.
- For percentage promos, the saving on a unit is
price * p / 100, so they prefer expensive units, while buy-get promos give a saving equal to the price of the free unit. A unit is worth more to whichever gives the larger saving. - When both compete, either run a small DP or min-cost-flow over (promotion, unit) assignments, or, for small carts, enumerate orderings of promotions and take the best. State the complexity honestly: the general problem with overlapping scopes and limits can be hard, so for production I would cap the number of active promotions and use the exact search only when it is small.
Return the minimum over the candidate plans, plus the "no promotion" baseline, so a promotion can never make the price worse.
If stacking on the same unit is allowed, the order matters. Percent-then-free-unit and free-unit-then-percent give different totals when a percentage applies to the remaining paid amount. I would define a fixed order (for example, buy-get first, then percent on the remaining paid amount) or evaluate both orders and keep the lower total, if the business rule says "best for the customer".
4. Example
Cart: 5 units of A at 10.00. Promotions: 20% off A; buy 2 get 1 free on A.
- No promo: 50.00.
- 20% off: 40.00.
- Buy 2 get 1:
5 // 3 = 1group, 1 free unit, cost 40.00. - Stacked (buy-get first, then 20% on the 4 paid units): 32.00.
If stacking is not allowed, the answer is 40.00; if it is, 32.00. The same input yields different "correct" answers depending on the assumption, so the assumption must be stated.
5. Edge cases
- Quantity below the threshold (qty < X+Y): the buy-get promo gives nothing. Decide whether a partial group such as buying X with qty between X and X+Y-1 gives a free item (usually not).
- Percent of 0 or 100, or more than 100: validate and reject or clamp.
- Zero price items, empty cart, and zero quantity.
- Ties between promotions: pick deterministically, for example by promotion id, so results are reproducible.
- Promotions with a usage limit smaller than the number of possible groups.
6. Rounding
Use integers. Compute price_cents * qty * (100 - p), then divide by 100 with a defined rounding mode. Rounding per unit versus per line can differ by a few cents, so pick one and document it. Never use binary floating point for money.
7. Complexity
- Case A:
O(N * P)for N lines and P promotions. - Case B with sorting:
O(U log U + P*U)for U units, with an exact search that is exponential in the number of overlapping promotions in the worst case.
8. Testing
- Property test: the result is never greater than the undiscounted total and never negative.
- Adding a promotion never raises the best price.
- Compare against a brute-force enumerator on small random carts.
- Shuffling the order of items or promotions yields the same total.
- Golden tests for the boundary quantities (X+Y-1, X+Y, 2(X+Y)) and for rounding cases such as 33.33% on awkward prices.
Common mistakes
- Returning a number without stating the stacking and rounding rules.
- Making the most expensive unit free instead of the cheapest.
- Applying the percent discount to the original price after already giving free units, which double counts.
- Using floats for currency.
- Ignoring repeats and usage caps.
- Choosing a greedy rule without checking that it is optimal when promotions overlap.