The Product of the Last K Numbers problem asks us to design a data structure that ingests numbers from a stream and computes the product of the last k inserted elements on demand. It is a classic variation of the prefix product technique that tests your ability to handle zero resets cleanly in O(1) time.
The problem
We need to build a class ProductOfNumbers with two methods:
add(num): Appends an integernumto the running stream.getProduct(k): Calculates and returns the product of the lastkintegers added to the stream.
For example, consider the following sequence of operations:
add(4): Stream is[4]add(3): Stream is[4, 3]add(2): Stream is[4, 3, 2]getProduct(2): Returns product of last 2 elements (3 * 2 = 6)add(0): Stream is[4, 3, 2, 0]add(5): Stream is[4, 3, 2, 0, 5]add(2): Stream is[4, 3, 2, 0, 5, 2]getProduct(2): Returns product of last 2 elements (5 * 2 = 10)getProduct(4): Returns0because the last 4 elements[2, 0, 5, 2]include a zero.
Computing the product by iterating back k elements every time would take O(k) time. When k is up to 40,000 and there are 40,000 queries, an O(k) approach will TLE (Time Limit Exceeded). We need both operations to run in O(1) time.
The key idea
Just as prefix sums allow computing range sums in O(1) time (which you can review in our prefix sums guide), prefix products allow computing contiguous range products using division. If prefix[i] stores the product of all elements from index 0 to index i, then the product of elements in range [i, j] is:
product(i..j) = prefix[j] / prefix[i - 1]
However, division breaks when zeros enter the sequence. Dividing by zero causes arithmetic errors, and once a zero enters a product, all subsequent cumulative products become zero, destroying previous historical product data.
The key breakthrough is realizing that zero acts as a hard boundary:
- Any
getProduct(k)query whose window spans across a zero will immediately result in0. - Any
getProduct(k)query whose window sits entirely after the latest zero can ignore all numbers added before that zero.
Because of this property, whenever we encounter a 0, we can clear our prefix product list and start fresh with a clean slate [1].
When getProduct(k) is called:
- If
kis greater than or equal to the current length of ourprefixarray, it means the requested window reaches back to or past a zero. We instantly return0. - Otherwise, the product is simply
prefix[last] / prefix[last - k].
Let us trace our example step-by-step:
- Initialize:
prefix = [1] add(4):prefix = [1, 4]add(3):prefix = [1, 4, 12]add(2):prefix = [1, 4, 12, 24]getProduct(2): Array length is 4.k = 2 < 4. Result =prefix[3] / prefix[3 - 2] = 24 / 4 = 6.add(0): Zero detected. Resetprefix = [1].add(5):prefix = [1, 5]add(2):prefix = [1, 5, 10]getProduct(2): Array length is 3.k = 2 < 3. Result =prefix[2] / prefix[2 - 2] = 10 / 1 = 10.getProduct(4): Array length is 3.k = 4 >= 3. Window spans past zero reset point, so return0.
Approach
- Maintain a list
prefixinitialized with a single dummy element[1]. The dummy element simplifies boundary math so we do not need special cases for taking the product of all elements added since the last reset. - In
add(num):- If
num == 0, resetprefixto[1]. - If
num != 0, calculateprefix.last * numand append it toprefix.
- If
- In
getProduct(k):- Check if
k >= len(prefix). - If true, return
0(the requested window includes a zero). - Otherwise, return
prefix[len(prefix) - 1] / prefix[len(prefix) - 1 - k].
- Check if
Code
class ProductOfNumbers:
def __init__(self):
self.prefix = [1]
def add(self, num: int) -> None:
if num == 0:
self.prefix = [1]
else:
self.prefix.append(self.prefix[-1] * num)
def getProduct(self, k: int) -> int:
if k >= len(self.prefix):
return 0
return self.prefix[-1] // self.prefix[-1 - k]Complexity
- Time Complexity:
add(num): O(1) amortized time. Appending to dynamic arrays takes O(1) time. Resetting the array via.clear()in Java/C++ or re-assigning in Python/JS runs in O(1) amortized time.getProduct(k): O(1) time. It involves a single length check and one integer division operation.
- Space Complexity: O(N) auxiliary space, where N is the total number of calls to
addsince the last zero. In the worst case where no zeros are added, we store up to 40,000 elements in the prefix array.
Edge cases and common mistakes
- Off-by-one errors in condition: A common mistake is using
k > len(prefix)instead ofk >= len(prefix). Because our array contains a dummy1at index 0, if 2 valid numbers are added after zero,len(prefix)is 3.k = 2is valid (prefix[2] / prefix[0]), butk = 3spans past the zero reset point, sok >= len(prefix)correctly returns0. - Re-allocating list objects repeatedly: In languages like Java or C++, creating a
new ArrayList()insideadd(0)triggers memory allocation and garbage collection. Usingprefix.clear()reuses the allocated capacity and improves runtime performance during high-volume stream operations. - Integer overflow assumptions: In standard real-world applications, multiplying prefix products can quickly overflow 32-bit or 64-bit integers. In this specific LeetCode problem, constraints state that the cumulative product fits in a 32-bit signed integer.
Follow-ups an interviewer may ask
1. What if stream values can lead to 64-bit integer overflow?
If elements are large and products exceed integer limits, division-based prefix products fail. We can handle this in two ways:
- BigInteger: Use arbitrary-precision integer arithmetic (Python handles this natively; Java has
BigInteger). - Logarithms: Convert products to sum of logarithms:
log(a * b) = log(a) + log(b). Maintain a prefix sum array oflog(num). To get the product, computeexp(prefix_log[last] - prefix_log[last - k]). This converts multiplication to addition and prevents overflow, though floating-point precision issues must be managed.
2. What if stream inputs contain negative numbers?
Our solution works with negative numbers without any modification. In integer division, signs are preserved correctly (for example, -12 / -3 = 4 and 12 / -3 = -4). As long as zero is handled by resetting the array, negative numbers maintain standard mathematical properties under prefix division.
3. How would you support a popLast() operation that removes the most recent number?
If no zero was removed, popLast() is simply popping the last element from prefix in O(1) time. However, if the popped element was 0, we need to restore the prefix state prior to that zero. To support this, we would maintain a stack of previous prefix arrays or track zero position checkpoints so we can roll back state cleanly.
This is LeetCode problem 1352, Product Of The Last K Numbers, explained in our own words. CureBugs is not affiliated with LeetCode.