KatInterview

Build a Grouped, Promo-Aware, Sorted Receipt Printer

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designhash-maprefactoring

Last updated

Extend a cart class that turns scanned item names into a receipt: itemized total, grouping by type, a buy-three-get-two-free deal, then alphabetical ordering.

You are given a small ShoppingCart class that stores scanned items in a plain list. It has addItem and removeItem methods, and some existing code prints a receipt from it. Items arrive as a stream of name strings. Your job is to evolve the cart through four requirements, each building on the last. Most of the design effort belongs in the cart and its collaborators, not in the printing code.

Use these prices for the examples:

cheese 4.00    bread 2.50    apple 0.75
Stream: "cheese", "bread", "cheese", "apple", "cheese"

Requirement 1: itemized receipt. Print one line per scanned item, in scan order, with its price. End with a total line.

cheese 4.00
bread 2.50
cheese 4.00
apple 0.75
cheese 4.00
Total 15.25

Requirement 2: grouped receipt. Print one line per item type in the form name, quantity, unitPrice xquantity. Adding and removing items must still work, including removing the last unit of a type.

cheese, 3, 4.00 x3
bread, 1, 2.50 x1
apple, 1, 0.75 x1
Total 15.25

Requirement 3: promotion. Add a "buy three, get two free" deal for one specific item. The receipt line for that item must reflect the deal. All other items are unaffected.

Requirement 4: sorted receipt. Print the item lines in alphabetical order of name.

apple, 1, 0.75 x1
bread, 1, 2.50 x1
cheese, 3, 4.00 x3
Total 15.25

Before coding, state your assumptions: where prices come from, how money is stored and formatted, what happens on removing an absent item, how names are normalized (case, whitespace), and exactly what the promotion means for partial groups. Then explain your design and implement it, with attention to the cost of each cart operation and to how you would test it.

Hints

Hint 1

Store money as integer cents and format only at print time, so totals never suffer floating-point drift.

Hint 2

Replace the list with a map from item name to count. Add and remove become O(1), and removing the last unit of a type should delete the key so it never prints a zero-quantity line.

Hint 3

Model the promotion as a separate object that answers 'how many units are payable for this quantity?'. The cart and printer then only ask for payable units and never special-case an item.

Hint 4

Sort at print time (O(k log k) for k distinct types) rather than on every add, and normalize names to a single case so ordering and grouping agree.