Design a shopping cart class with add, remove, quantity updates and total price
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Other
Design a shopping cart that manages the items a user wants to purchase. The cart supports adding items with a unique ID, name, unit price and quantity. If an item that is already in the cart is added again, its quantity increases by the specified amount.
The cart also supports removing items entirely, updating the quantity of a specific item (removing it if the quantity drops to zero or below), and calculating the total price of all items in the cart.
It can also report the total number of individual items (the sum of quantities), list all current items sorted by item ID, and say whether the cart is empty.
Implement a class `ShoppingCart()` with these methods:
- `addItem(itemId: int, name: str, price: float, quantity: int)`: add an item to the cart. If an item with the same `itemId` already exists, increase its quantity by the given amount.
- `removeItem(itemId: int) -> bool`: remove the item with this `itemId` entirely. Return `True` if it was found and removed, `False` otherwise.
- `updateQuantity(itemId: int, quantity: int) -> bool`: set the quantity of an existing item. If `quantity` is 0 or negative, remove the item. Return `True` if the item existed, `False` otherwise.
- `getTotalPrice() -> float`: return the total price of all items (the sum of `price * quantity` over the items), rounded to 2 decimal places.
- `getItemCount() -> int`: return the total number of individual items (the sum of all quantities).
- `getItems() -> List[List]`: return every item as `[itemId, name, price, quantity]`, sorted by `itemId` in ascending order.
- `isEmpty() -> bool`: return `True` if the cart has no items, `False` otherwise.
Example 1:
```text
Input:
["ShoppingCart", "addItem", "addItem", "addItem", "getItemCount", "getTotalPrice", "getItems", "removeItem", "getTotalPrice", "getItems"]
[[], [3, "Milk", 3.49, 2], [1, "Eggs", 4.25, 1], [3, "Milk", 3.49, 1], [], [], [], [1], [], []]
Output: [null, null, null, null, 4, 14.72, [[1, "Eggs", 4.25, 1], [3, "Milk", 3.49, 3]], true, 10.47, [[3, "Milk", 3.49, 3]]]
Explanation:
cart = ShoppingCart() # empty cart
cart.addItem(3, "Milk", 3.49, 2) # cart: {3: Milk x2}
cart.addItem(1, "Eggs", 4.25, 1) # cart: {1: Eggs x1, 3: Milk x2}
cart.addItem(3, "Milk", 3.49, 1) # item 3 exists, so Milk becomes x3
cart.getItemCount() # -> 4 (1 + 3)
cart.getTotalPrice() # -> 14.72 (4.25 * 1 + 3.49 * 3 = 4.25 + 10.47)
cart.getItems() # -> [[1, "Eggs", 4.25, 1], [3, "Milk", 3.49, 3]] (sorted by ID)
cart.removeItem(1) # -> True (Eggs removed)
cart.getTotalPrice() # -> 10.47
cart.getItems() # -> [[3, "Milk", 3.49, 3]]
```
Example 2:
```text
Input:
["ShoppingCart", "isEmpty", "addItem", "isEmpty", "updateQuantity", "getItemCount", "updateQuantity", "isEmpty", "removeItem"]
[[], [], [10, "Bread", 2.99, 1], [], [10, 5], [], [10, 0], [], [10]]
Output: [null, true, null, false, true, 5, true, true, false]
Explanation:
cart = ShoppingCart() # empty cart
cart.isEmpty() # -> True (cart is empty)
cart.addItem(10, "Bread", 2.99, 1) # cart: {10: Bread x1}
cart.isEmpty() # -> False (cart has 1 item)
cart.updateQuantity(10, 5) # -> True (Bread qty updated to 5)
cart.getItemCount() # -> 5
cart.updateQuantity(10, 0) # -> True (qty 0, Bread removed)
cart.isEmpty() # -> True (cart is empty again)
cart.removeItem(10) # -> False (item 10 no longer exists)
```
```hint Lookups and money
Every operation names an item by `itemId`, so pick a structure that finds an item by ID in constant time. Then check what Python prints for `0.1 * 3` and decide how you want to store prices.
```
### Constraints & Assumptions
- `1 <= itemId <= 10^4`
- `1 <= quantity <= 1000` for `addItem`
- `0 <= quantity <= 1000` for `updateQuantity`
- `0.01 <= price <= 10000.00`
- Item names are non-empty strings of length at most 100.
- At most `10^4` calls are made to any method.
### Clarifying Questions to Ask
- When `addItem` is called for an ID already in the cart with a different name or price, should only the quantity change, or should the stored name and price be replaced too?
- Can a price have more than two decimal places, or are prices always whole cents?
- Should `getItems` return a copy, so a caller cannot change the cart by editing the returned lists?
- Can two sessions (for example two browser tabs) change the same cart at the same time?
### What a Strong Answer Covers
- A storage choice keyed by `itemId` that makes add, remove and update constant time, and how a repeated `addItem` merges into the existing entry.
- The removal rule in `updateQuantity` for zero or negative quantities, and the correct `True`/`False` return value of every method.
- How the item count and total are computed or maintained, and the cost of each method, including the sort in `getItems`.
- How money is represented so the total is correct to the cent.
- Edge cases such as an empty cart, removing a missing item, and adding an item again after it was removed.
### Follow-up Questions
- How would you add discounts, such as 10% off the whole cart or "buy two, get one free" on one item?
- An item's price changes while it sits in the cart. Which price should checkout use, and what would you store to support that?
- How would you persist the cart so it survives across sessions and devices?
- Two tabs update the same cart at once. How do you keep the quantities and the total consistent?
Overview: Implement a shopping cart class that adds items by ID, merges repeated adds, updates or removes quantities, and reports the total price, item count and a sorted item list. It tests choosing the right data structure, exact handling of money, and correct return values for edge cases.