KatInterview

Cart Pricing Engine: Offers, Cheapest Deal, Aisle Sort

Arrays & HashingModel answer
MediumModel answerArrays & Hashingparsingmoney-arithmeticextensible-design

Last updated

Parse cart records, total units and price in integer cents, apply the best percent-off or buy-N-get-M-free deal per product, then sort items by aisle with frozen goods at the end.

You are building the checkout logic for an online grocery cart. The cart arrives as text, one product per line. Build it in three stages, and agree on the input format and rules before you start coding.

For concreteness, assume this format (you may propose another, but state it):

name,unit_price,quantity,aisle,frozen
milk,3.49,2,4,no
pizza,6.00,3,9,yes
apples,0.50,6,,no

Offers are given separately:

milk: 10% off
pizza: buy 2 get 1 free
pizza: 25% off

Stage 1: Totals

Parse every record and report:

  • the total number of units in the cart
  • the total price

Decide how to handle malformed lines (wrong field count, non-numeric or negative values, bad quantity), a product that appears on several lines, and a missing aisle. Use an exact money representation.

Stage 2: Offers

Support two offer types:

  • Percentage off: a product's price is reduced by a given percent.
  • Buy N, get M free: for every group of N paid units, M further units are free.

A product may have several offers. Only the one that gives that product the lowest price applies; offers are never combined. Report the total discount in addition to the final price. Think about quantities that do not fill a whole group (for example 5 units under "buy 2 get 1 free") and where percentage results are rounded.

Adding a third offer type later should not require changes to the totals code.

Stage 3: Ordering

Return the cart items sorted by aisle, with all frozen items after every non-frozen item. Define what happens with ties and with items that have no aisle.

Expected

Working code (or detailed pseudocode), the rules you chose and why, and the complexity of each stage.

Hints

Hint 1

Store money as integer cents and parse the price text with a decimal type, not a float. Round only once, at a clearly defined point (for example per product line), with an explicit rule such as half-up.

Hint 2

For buy N get M free, a full group is N+M units and costs N units. Leftover units cost min(leftover, N) units. Compute every candidate cost for a product, including full price, and take the minimum.

Hint 3

Model each offer as an object with a method that returns the cost of a line, so totals only call that method. For ordering, a single sort with a tuple key such as (is_frozen, aisle_missing, aisle, name) does everything, and sort stability gives deterministic ties.