Python 1352.py
class ProductOfNumbers:
def __init__(self):
self.data = []
def add(self, num: int) -> None:
self.data.append(num)
def getProduct(self, k: int) -> int:
return prod(self.data[-k:])
Difficulty
and has an acceptance rate of about 63% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Data Stream
- Design
- Math
- Prefix Sum
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 ProductOfNumbers class provides a minimal interface for building a sequence of integers and retrieving the product of the last k elements. Internally it stores the numbers in a Python list and relies on the standard library’s prod function to compute the product on demand.
Core Components
Initialization
def __init__(self):
self.data = []
When an instance is created, an empty list named data is allocated. This list serves as the dynamic container for all numbers added through the add method.
Adding a Number
def add(self, num: int) -> None:
self.data.append(num)
The add method receives an integer and appends it to the end of self.data. Using the list’s append operation ensures that insertion occurs in amortized constant time, preserving the order of insertion.
Retrieving a Product
def getProduct(self, k: int) -> int:
return prod(self.data[-k:])
getProduct extracts a slice consisting of the last k elements (self.data[-k:]) and passes that slice to prod. The slice operation creates a new list containing exactly the elements needed for the calculation, and prod multiplies them sequentially, returning the final product.
Edge-Case Handling
The implementation gracefully manages several boundary conditions without explicit checks.
When k equals zero, the slice self.data[-0:] evaluates to an empty list. The prod function defines the product of an empty iterable as 1, so getProduct(0) correctly returns 1.
If k exceeds the current length of self.data, the slice returns the entire list. Consequently, getProduct yields the product of all stored numbers, which aligns with the intuitive expectation for “the product of the last k elements” when fewer than k elements exist.
Negative numbers are treated like any other integer; the multiplication performed by prod naturally incorporates sign changes, delivering the mathematically correct result.
The class also tolerates repeated calls to add and getProduct in any order, because each method operates solely on the current state of self.data without side effects.
Performance Optimizations Observed
The design leverages two built-in operations that are already highly optimized in CPython.
Appending to a list is an O(1) amortized operation, and the underlying list implementation over-allocates memory to minimize the frequency of resizing. This means that a large number of add calls will not incur significant allocation overhead.
The prod function, introduced in Python 3.8, is implemented in C. By delegating the multiplication to this native routine, the code avoids the overhead of a Python-level loop. Even though a slice is created, the slice operation itself is a fast memory copy of references, and the subsequent C-level multiplication benefits from low-level optimizations such as loop unrolling and efficient integer arithmetic.
Together, these choices keep the runtime of both add and getProduct low for typical usage patterns, especially when the number of elements and the value of k remain moderate.
ELI5 - Simplified Explanation
Imagine having a special toy box where you can put numbers inside one by one. The first part of the code acts like a magical helper that builds an empty toy box to store all the numbers provided. Whenever a new number is given, the helper picks it up and places it securely inside the box. When it is time to do math, the helper looks at the very end of the box and grabs the last few numbers mentioned. The helper then multiplies those specific numbers together to find the final result. It works exactly like a line of building blocks where the helper only ever cares about the ones placed most recently.
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 | JS | Java | Go | TS | ||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| Shamik07 | Dart | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| Shamik07 | Dart | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 483: Smallest Good Base
- problem 1032: Stream of Characters
- problem 1825: Finding MK Average
- problem 2102: Sequentially Ordinal Rank Tracker
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