Apply Discount Every n Orders

The problem asks to implement a class Cashier that simulates the billing system at a supermarket with a discount applied to every nth customer. We’ll implement this class using two functions:

  1. __init__: Initializes the object with the given values.
  2. getBill: Returns the total bill after applying any applicable discounts.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Cashier:
    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.n = n
        self.discount = discount
        self.prices = {product: price for product, price in zip(products, prices)}
        self.customer_count = 0

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.customer_count += 1
        subtotal = sum(self.prices[product[i]] * amount[i] for i in range(len(product)))

        # Applying discount if this is the nth customer
        if self.customer_count % self.n == 0:
            return subtotal * ((100 - self.discount) / 100)
        return subtotal

Key Takeaways

  • Storing Products and Prices: We store the products and prices as a dictionary to make the lookup efficient.
  • Discount Application: A discount is applied only when the current customer count is divisible by n.
  • Time Complexity: Both the initialization and the getBill function work in O(1) time for each call, except for the sum operation inside getBill, which takes O(p) time, where p is the length of the product list for that particular call. Hence, the overall time complexity for each call to getBill is O(p).
  • Space Complexity: We are storing the products and prices in a dictionary, so the space complexity is O(p), where p is the number of products.