Apply Discount Every n Orders — LeetCode 1357 Python Solution

MediumDesignArrayHash Table
Problem
#1357
Pattern
Hash Map
Reading time
4 min

The problem

There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].

Example

Input
["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]
Output
[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]
Explanation
Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);

Python solution

Python
class Cashier:
    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.i = 0
        self.n = n
        self.discount = discount
        self.d = {product: price for product, price in zip(products, prices)}

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.i += 1
        discount = self.discount if self.i % self.n == 0 else 0
        ans = 0
        for p, a in zip(product, amount):
            x = self.d[p] * a
            ans += x - (discount * x) / 100
        return ans


# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1357. Apply Discount Every n Orders is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1357. Apply Discount Every n Orders?
LeetCode 1357. Apply Discount Every n Orders is rated Medium on LeetCode.
What is the time complexity of LeetCode 1357. Apply Discount Every n Orders?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1357. Apply Discount Every n Orders?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1357. Apply Discount Every n Orders cover?
LeetCode 1357. Apply Discount Every n Orders is tagged Design, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview