We need to design a checkout system that calculates customer bills and applies a percentage discount to every nth customer. This problem is a great exercise in basic object-oriented design, state management, and using hash maps for fast data retrieval.
The problem
Imagine you are building the billing software for a local cafe. You are given a list of menu items and their corresponding prices. The cafe owner wants to run a promotion: every nth customer gets a specific percentage discount on their entire order.
You need to implement a class that initializes the menu and processes each customer's order. For every order, you must calculate the total cost, apply the discount if the customer is eligible, and return the final bill.
Let us look at a custom example. Suppose the cafe sells Coffee (ID 10) for $3 and Bagels (ID 20) for $5. The promotion states that every 2nd customer gets 20% off.
- Customer 1 buys 2 Coffees. Their subtotal is 2 * $3 = $6. Since they are the first customer, they pay the full $6.
- Customer 2 buys 1 Bagel. Their subtotal is 1 * $5 = $5. Since they are the second customer, they get 20% off. They pay $5 * ((100 - 20) / 100) = $4.
- Customer 3 buys 1 Coffee and 1 Bagel. Their subtotal is $3 + $5 = $8. They pay the full $8.
The key idea
The core of this problem is efficiently looking up product prices and keeping track of how many customers have been served.
When the class is initialized, we receive two parallel arrays: one for product IDs and one for prices. If we search through the arrays every time a customer buys an item, it will be too slow. Instead, we can pair the IDs and prices together in a hash map. A hash map allows us to look up the price of any product in constant time.
Next, we need a way to track the discount eligibility. We can use an integer counter that starts at zero. Every time the billing method is called, we add one to this counter. If the counter is a multiple of the target frequency (meaning the remainder of the counter divided by the frequency is zero), we apply the discount.
Here is a visual representation of the class structure:
Let us trace our cafe example step-by-step:
- We initialize the system with frequency
2and discount20. We store the prices in a map:{10: 3, 20: 5}. The customer count is0. - Customer 1 arrives. We increment the count to
1. We look up ID 10, find the price $3, and multiply by the amount 2. Total is $6. Since 1 is not a multiple of 2, we return $6. - Customer 2 arrives. We increment the count to
2. We look up ID 20, find the price $5, and multiply by the amount 1. Total is $5. Since 2 is a multiple of 2, we apply the 20% discount. We return $4.
Approach
- Initialize the state: In the constructor, save the discount frequency and the discount percentage as instance variables.
- Build the price map: Create a hash map. Loop through the given product IDs and prices, inserting each pair into the map. This sets up our fast lookup table.
- Initialize the counter: Set an instance variable for the customer count to zero.
- Process the bill: Inside the billing method, first increment the customer count by one.
- Calculate the subtotal: Create a variable to hold the total cost. Loop through the purchased products. For each product, retrieve its price from the hash map, multiply it by the purchased amount, and add it to the total.
- Apply the discount: Check if the current customer count modulo the frequency equals zero. If it does, multiply the total by
(100 - discount) / 100.0. - Return the result: Return the final calculated total.
Code
class Cashier:
def __init__(self, n: int, discount: int, products: list[int], prices: list[int]):
self.n = n
self.discount = discount
self.customer_count = 0
# Create a hash map for O(1) price lookups
self.prices = {prod: price for prod, price in zip(products, prices)}
def getBill(self, product: list[int], amount: list[int]) -> float:
self.customer_count += 1
total = 0.0
# Calculate the subtotal
for p, a in zip(product, amount):
total += self.prices[p] * a
# Apply discount if the customer is the nth customer
if self.customer_count % self.n == 0:
total *= (100 - self.discount) / 100.0
return totalComplexity
Let P be the number of unique products in the catalog, and I be the number of items a customer purchases in a single bill.
- Time Complexity:
Constructor: O(P). We iterate through the given arrays of sizePonce to populate the hash map. Inserting into a hash map takes O(1) time on average.getBill: O(I). We iterate through theproductarray provided in the method call. For each item, we perform an O(1) lookup in our hash map. The discount calculation takes O(1) time.
- Space Complexity: O(P). We store all
Pproducts and their prices in a hash map. The space required grows linearly with the number of products in the catalog.
Edge cases and common mistakes
In languages like Java and C++, dividing two integers results in an integer. If you write (100 - discount) / 100, it will evaluate to 0 for any discount greater than zero. You must ensure at least one operand is a floating-point number, for example by writing 100.0.
Another edge case is floating-point precision. While standard double-precision floats are usually fine for coding interviews, real-world financial systems avoid them because they cannot accurately represent certain decimals (like 0.1). In a production environment, you would store prices in cents using integers or use specialized classes like BigDecimal in Java.
Finally, remember that the customer count is 1-based, not 0-based. The first customer to check out is customer 1. If you increment the counter after checking the modulo condition, your logic will be off by one.
Follow-ups an interviewer may ask
1. What happens if multiple cashiers process bills at the exact same time?
If multiple threads call getBill concurrently, we have a race condition on customerCount. Two threads might read the same value, increment it, and write it back, causing us to lose a count and miss a discount. To fix this, we should use atomic variables (like AtomicInteger in Java) or wrap the increment logic in a synchronized block. You can read more about this in our guide on /learn/processes-threads-and-concurrency.
2. How would you handle dynamic price updates during the day?
We could add an updatePrice(productId, newPrice) method. However, if prices are updated while a bill is being processed, it could lead to inconsistent totals. We would need to implement read-write locks. The getBill method would acquire a read lock, allowing multiple bills to be processed simultaneously, while updatePrice would acquire an exclusive write lock to ensure no bills are processed during the update.
3. What if the product catalog is too large to fit in memory?
If we have millions of products, storing them all in a hash map might exceed our server's RAM. We would need to store the catalog in a database. To keep the getBill method fast, we could implement a caching layer (like an LRU cache) to keep frequently bought items in memory while fetching rare items from the database. Check out /learn/lld-lru-cache and /learn/caching-strategies for more details.
4. How would you handle invalid product IDs in an order?
Currently, our code assumes all product IDs in the order exist in the catalog. In a real system, a cashier might scan an invalid barcode. We should add error handling: check if the product exists in the map before retrieving its price. If it is missing, we could throw an exception or skip the item and log a warning.