Product of the Last K Numbers Problem
Description
LeetCode Problem 1352.
Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.
Implement the ProductOfNumbers class:
ProductOfNumbers()Initializes the object with an empty stream.void add(int num)Appends the integernumto the stream.int getProduct(int k)Returns the product of the lastknumbers in the current list. You can assume that always the current list has at leastknumbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
Example:
Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
Output
[null,null,null,null,null,null,20,40,0,null,32]
Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // [3]
productOfNumbers.add(0); // [3,0]
productOfNumbers.add(2); // [3,0,2]
productOfNumbers.add(5); // [3,0,2,5]
productOfNumbers.add(4); // [3,0,2,5,4]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0
productOfNumbers.add(8); // [3,0,2,5,4,8]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32
Constraints:
0 <= num <= 1001 <= k <= 4 * 10^4- At most
4 * 10^4calls will be made toaddandgetProduct. - The product of the stream at any point in time will fit in a 32-bit integer.
Follow-up: Can you implement both GetProduct and Add to work in O(1) time complexity instead of O(k) time complexity?
Solution
Approach: Prefix Products, Reset on Zero
With prefix sums, the sum of the last k numbers is a difference of two prefix sums. Products work the same way with division: keep prefix[i], the product of the first i numbers, and the product of the last k numbers is prefix[last] / prefix[last - k].
Zeros break the division, so handle them separately. Once a 0 is added, every window that reaches back past it has product 0. So when add(0) is called, throw away the prefix list and start again from [1]. The list then only covers the numbers after the last zero:
add(num)withnum != 0appendsprefix[-1] * num.getProduct(k): ifkis at least the length of the list, the lastknumbers reach back to a zero, so return0. Otherwise returnprefix[-1] / prefix[-1 - k].
The division is always exact, and because the product of any run of numbers fits in 32 bits, so does every entry of the list. The extra 1 at the front makes a query that covers all numbers since the last zero work too.
Complexity: O(1) time for both operations, and O(n) space for the n added numbers.
class ProductOfNumbers:
def __init__(self):
# prefix[i] = product of the first i numbers after the last 0
self.prefix = [1]
def add(self, num: int) -> None:
if num == 0:
self.prefix = [1] # every window that reaches back past here is 0
else:
self.prefix.append(self.prefix[-1] * num)
def getProduct(self, k: int) -> int:
if k >= len(self.prefix):
return 0 # the last k numbers include a 0
return self.prefix[-1] // self.prefix[-k - 1]
# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)