SDE & MLE Prep

1352. Product of the Last K Numbers

Problem

Design ProductOfNumbers for a stream of non-negative integers: add(num) appends a number and getProduct(k) returns the product of the last k numbers (k never exceeds the count so far; products fit in 32 bits).

Example: add 3, 0, 2, 5, 4 → getProduct(2) = 20, getProduct(3) = 40, getProduct(4) = 0; add 8 → getProduct(2) = 32

Constraints: follow-up: O(1) per call.

Keep prefix products; a 0 resets the list (any window containing it is 0). getProduct(k) = pre[-1] / pre[-1-k], or 0 if k reaches past the last reset.

Complexity: O(1) per operation.

class ProductOfNumbers:
    def __init__(self):
        self.pre = [1]

    def add(self, num: int) -> None:
        if num == 0:
            self.pre = [1]
        else:
            self.pre.append(self.pre[-1] * num)

    def getProduct(self, k: int) -> int:
        if k >= len(self.pre):
            return 0
        return self.pre[-1] // self.pre[-1 - k]