41. Design a Shopping Cart
Design a Shopping Cart
Design a simple in-memory Shopping Cart that uses an initial item catalog
and lets a user add items by ID, view their cart, and checkout.
It also enforces unknown item ID, insufficient stock, and empty-cart checkout.
Methods
- ShoppingCart(List<String> items)
- Each row in items is a comma-separated string: itemId,pricePerUnit,unitsAvailable.
- Example: coca-cola-pack,8,12 means 12 units of coca-cola-pack available, each costing 8 dollars.
- itemId contains only a-z and hyphen -.
- Each itemId is non-blank and unique.
- pricePerUnit and unitsAvailable are positive integers < 1000.
- String addItem(String itemId, int count)
- count is always a positive integer.
- If itemId doesn't exist in catalog ⇒ return UNAVAILABLE.
- If itemId exists but has less than count units available ⇒ return OUT OF STOCK.
- If item is correctly added ⇒ return SUCCESS.
- If an item is already in the cart, simply add count to its existing units.
- List<String> viewCart()
- Returns current cart items sorted by itemId (lexicographically).
- Each row is itemId,itemCount.
- If cart is empty, return an empty list.
- int checkout()
- Compute total cost as sum of pricePerUnit * itemCount for all items in cart.
- Clear the cart and return this total.
- after checkout, the initial items count is not reset. - e.g. if out of 12 coca-cola-pack 3 were ordered then after checkout ,
9 coca-cola-pack units will remain, they will not reset to 12 again. - If cart is empty, return -1.
Example Scenarios
Example 1 – Normal Flow
ShoppingCart cart = new ShoppingCart(Arrays.asList(
"coca-cola-pack,8,12",
"juice-box,5,10"
));
String r1 = cart.addItem("coca-cola-pack", 2); // "SUCCESS"
String r2 = cart.addItem("juice-box", 3); // "SUCCESS"
List<String> view = cart.viewCart();
// view = ["coca-cola-pack,2", "juice-box,3"] (sorted by itemId)
int total = cart.checkout();
// total = 2*8 + 3*5 = 31
// cart is now empty; cart.viewCart() returns []
Example 2 – Out of Stock
ShoppingCart cart = new ShoppingCart(Arrays.asList(
"laptop,900,1"
));
String r1 = cart.addItem("laptop", 2);
// r1 = "OUT OF STOCK"
// cart.viewCart() = [] (still empty)
Example 3 – Unavailable Item & Empty Checkout
ShoppingCart cart = new ShoppingCart(Arrays.asList(
"book,50,2"
));
String r1 = cart.addItem("pen", 1);
// r1 = "UNAVAILABLE"
// cart.viewCart() = [] (cart still empty)
int total = cart.checkout();
// total = -1 (cannot checkout empty cart)