Problem statement

https://binarysearch.com/problems/Sliding-Window-Product/

Solution

Keep cumulative products and also keep the place of last zero.

Complexity

It is O(1) for time for all operations and O(n) for total space.

Code

class SlidingWindowProduct:
    def __init__(self):
        self.arr = [1]
        self.prod = 1
        self.last_zero = -1

    def add(self, num):
        if num == 0:
            self.last_zero = len(self.arr)
            self.arr += [1]
        else:
            self.arr += [self.arr[-1] * num]

    def product(self, k):
        if self.last_zero >= len(self.arr) - k:
            return 0
        else:
            return self.arr[-1]//self.arr[-k-1]