Problem 1357

Abstract / Summary

Calculate the total cost of items bought with a discount applied every n orders.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 585 bytes | submitted November 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (40k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.38 | σ = 1.21

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
25 links | 13 authors | 8 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   November 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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