Product of the Last K Numbers (LeetCode 1352): Solution and Explanation
Design a stream that supports add(num) and getProduct(k), the product of the last k numbers, both in constant time.
Intuition
Multiplying the last k numbers on every query costs O(k), which is too slow when there are tens of thousands of calls.
Prefix sums answer any range sum with one subtraction. Prefix products do the same with one division: if prefix[i] is the product of the first i numbers, the last k numbers multiply to prefix[-1] / prefix[-1-k].
The only thing that breaks division is a zero. But a zero also makes every product that reaches back past it equal to 0, so the history before it is useless. Throw it away and restart the prefix list at 1.
Approach: Prefix products with reset on zero
- Start with
prefix = [1], the empty product. add(num): ifnumis 0, resetprefixto[1]. Otherwise appendprefix[-1] * num.getProduct(k): ifk >= len(prefix), fewer than k numbers have arrived since the last 0, so the window contains that 0. Return 0.- Otherwise return
prefix[-1] / prefix[-1 - k].
Step-by-step example
add 3, 0, 2, 5, 4; getProduct 2, 3, 4; add 8; getProduct 2
- add(3): prefix = [1, 3]. add(0): reset, prefix = [1].
- add(2), add(5), add(4): prefix = [1, 2, 10, 40].
- getProduct(2) = 40 / prefix[1] = 40 / 2 = 20. getProduct(3) = 40 / 1 = 40.
- getProduct(4): 4 >= len(prefix) = 4, so the window reaches the 0. Return 0.
- add(8): prefix = [1, 2, 10, 40, 320]. getProduct(2) = 320 / 10 = 32.
Code: Python, Java, C++
1class ProductOfNumbers:
2 def __init__(self):
3 self.prefix = [1]
4
5 def add(self, num: int) -> None:
6 if num == 0:
7 self.prefix = [1]
8 else:
9 self.prefix.append(self.prefix[-1] * num)
10
11 def getProduct(self, k: int) -> int:
12 if k >= len(self.prefix):
13 return 0
14 return self.prefix[-1] // self.prefix[-1 - k]1class ProductOfNumbers {
2 private List<Long> prefix;
3
4 public ProductOfNumbers() {
5 prefix = new ArrayList<>();
6 prefix.add(1L);
7 }
8
9 public void add(int num) {
10 if (num == 0) {
11 prefix = new ArrayList<>();
12 prefix.add(1L);
13 } else {
14 prefix.add(prefix.get(prefix.size() - 1) * num);
15 }
16 }
17
18 public int getProduct(int k) {
19 int n = prefix.size();
20 if (k >= n) {
21 return 0;
22 }
23 return (int) (prefix.get(n - 1) / prefix.get(n - 1 - k));
24 }
25}1class ProductOfNumbers {
2 vector<long long> prefix;
3
4public:
5 ProductOfNumbers() {
6 prefix = {1};
7 }
8
9 void add(int num) {
10 if (num == 0) {
11 prefix = {1};
12 } else {
13 prefix.push_back(prefix.back() * num);
14 }
15 }
16
17 int getProduct(int k) {
18 int n = prefix.size();
19 if (k >= n) {
20 return 0;
21 }
22 return (int) (prefix[n - 1] / prefix[n - 1 - k]);
23 }
24};Time and space complexity
O(1) per call
add appends one value or resets the list, and getProduct does one comparison and one division.
O(n)
The prefix list holds at most one entry per number added since the last zero.
Other approaches
Multiply on demand (time O(k) per query, space O(n))
Store the raw stream and multiply the last k values on each query. Simple, but getProduct costs O(k).
Track the last zero position (time O(1) per call, space O(n))
Keep one global prefix list where zeros are skipped, plus the index of the last zero. Equivalent, but the reset version is shorter.
Common mistakes
- Appending 0 to the prefix list. Every later prefix becomes 0 and the division turns into 0 / 0.
- Off-by-one on the zero check. The list has len(prefix) - 1 real numbers, so k numbers fit only when k < len(prefix).
- Storing prefixes in a 32-bit int. A single product fits, but a prefix of many numbers can be larger than any one answer, so use 64-bit values in typed languages.
Frequently asked questions
Why is the division always exact?
prefix[-1] is prefix[-1-k] multiplied by the last k numbers, none of which is 0, so the quotient is exactly their product.
Why can the old prefixes be discarded on a zero?
Any window that reaches back past the zero includes it, so its product is 0 no matter what came before. The only information needed is how many numbers came after the zero, and that is the length of the new list.
Can prefix products overflow?
In principle a long run of numbers above 1 makes prefixes larger than any single answer. Using 64-bit integers covers the test data; Python integers never overflow.