Python 1357.py
class Cashier:
def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
self.items = { pro : pri for pro, pri in zip(products, prices) }
self.discount = (100 - discount) / 100
self.trigger = n
self.people = 0
def getBill(self, product: List[int], amount: List[int]) -> float:
cost = sum( self.items[p] * a for p, a in zip(product, amount) )
self.people += 1
if self.people == self.trigger:
self.people = 0
cost *= self.discount
return cost
Difficulty
and has an acceptance rate of about 66% (40k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Hash Table
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Cashier class models a point-of-sale system that tracks product prices, counts customers, and applies a periodic discount after a configurable number of purchases. The constructor receives the trigger count, discount percentage, and parallel arrays of product identifiers and their unit prices. The getBill method computes the total for a given transaction, updates the internal customer counter, and conditionally applies the discount.
Initialization
During object creation the code builds a dictionary that maps each product identifier to its price. This is achieved with a dictionary comprehension that zips the products and prices lists, ensuring constant-time lookup for any product later on. The discount factor is pre-computed as a multiplier by converting the percentage into a fractional reduction, which avoids repeated arithmetic in the billing routine. The trigger count n and a counter for processed customers are stored as instance attributes.
self.items = { pro : pri for pro, pri in zip(products, prices) }
self.discount = (100 - discount) / 100
self.trigger = n
self.people = 0
Billing Calculation
getBill receives two parallel lists: product (identifiers) and amount (quantities). The total cost is calculated by iterating over both lists simultaneously with zip, multiplying each unit price retrieved from the dictionary by the requested quantity, and summing the results. The use of a generator expression inside sum keeps memory usage low because intermediate values are not stored in a separate list.
cost = sum(self.items[p] * a for p, a in zip(product, amount))
Discount Application
After the raw cost is obtained, the method increments the internal customer counter. When the counter reaches the configured trigger value, it resets to zero and applies the pre-computed discount multiplier to the current transaction total. This logic ensures that the discount is applied exactly once for every n-th customer, regardless of how many times getBill is called.
self.people += 1
if self.people == self.trigger:
self.people = 0
cost *= self.discount
Edge Cases
The implementation gracefully handles several edge conditions. If a transaction includes a product identifier that does not exist in the price dictionary, a KeyError would be raised, which signals a mismatch between the supplied product list and the initialized catalog; this behavior is appropriate for a strict inventory system. When the amount list contains zero or negative quantities, the multiplication yields zero or a negative contribution to the sum, allowing the caller to represent returns or adjustments without additional code. The discount factor calculation works for a discount of zero (resulting in a multiplier of 1.0) and for a full discount of 100 % (resulting in 0.0), correctly handling the extremes of the discount range.
Performance Considerations
The dictionary created at initialization provides O(1) average lookup for each product price, which is essential for fast billing when the catalog contains many items. By pre-computing the discount multiplier, the code avoids repeated division operations during each call to getBill. The generator expression used in the sum avoids allocating an intermediate list, reducing memory pressure for large transactions. The counter reset logic uses a simple equality check and assignment, keeping the per-call overhead minimal. Overall, the design emphasizes constant-time price retrieval and minimal per-transaction computation, making it well-suited for high-throughput checkout scenarios.
ELI5 - Simplified Explanation
Think of this code as a helper for a grocery store. The first part, called the constructor, sets up the shop. It makes a little dictionary that remembers exactly how much every item costs, figures out what the special discount percentage is, and prepares a counter to keep track of every customer who walks through the door.
When a customer comes to the checkout counter with a basket of groceries, the getBill part starts working. It looks at every item in the basket and adds up the price of each one to find the total. Every single time a customer finishes their transaction, the counter adds one more person to the list. If that number matches the magic goal number, the discount is applied to that specific bill to make it cheaper, and the counter resets back to zero so the fun can start all over again for the next group of shoppers.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2288: Apply Discount to Prices
Solved On The Same Day
- problem 1365: How Many Numbers Are Smaller Than the Current Number
- problem 1389: Create Target Array in the Given Order
- problem 1394: Find Lucky Integer in an Array
- problem 1758: Minimum Changes To Make Alternating Binary String
- problem 1362: Closest Divisors
- problem 1367: Linked List in Binary Tree
- problem 1386: Cinema Seat Allocation
- problem 1390: Four Divisors
- problem 1395: Count Number of Teams
- problem 1759: Count Number of Homogenous Substrings
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality