Simple solution |  prefix product 
IntuitionEven though we can brute force the solution using a O(n) approach, we can calculate prefix products.
If we encounter a 0, we will clear the prefix arra
# Intuition
Even though we can brute force the solution using a O(n) approach, we can calculate prefix products.
If we encounter a 0, we will clear the prefix array, else, store the product.
# Approach
add function:
1. If we encounter a 0, i.e. num=0, we will clear the prefix vector.
2. Else we will calculate the new product and push back to the prefix vector.

getProduct function:
1. If the size of the prefix vector is less than k, it means that we have a 0 within the previous k elements, so return 0.
2. Else return the prefix[len-1]/prefix[len-k-1];
# Complexity
- Time complexity:
O(1)
- Space complexity:
O(n)
# Code
```cpp []
class ProductOfNumbers {

private:
    vector<int>prefix;

public:
    ProductOfNumbers() {
        prefix.clear();
        prefix.push_back(1);
    }
    
    void add(int num) {
        if(num==0){prefix.clear();prefix.push_back(1);}
        else{
            prefix.push_back(prefix.back()*num);
        }
    }
    
    int getProduct(int k) {
        if(prefix.size()<=k){return 0;}
        int len = prefix.size();
        return prefix[len-1]/prefix[len-k-1];
    }
};

```

```Java []
class ProductOfNumbers {
    private List<Integer> prefix;

    public ProductOfNumbers() {
        prefix = new ArrayList<>();
        prefix.add(1);
    }

    public void add(int num) {
        if (num == 0) {
            prefix.clear();
            prefix.add(1);
        } else {
            prefix.add(prefix.get(prefix.size() - 1) * num);
        }
    }

    public int getProduct(int k) {
        if (prefix.size() <= k) {
            return 0;
        }
        int len = prefix.size();
        return prefix.get(len - 1) / prefix.get(len - k - 1);
    }
}
```

```python []
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 len(self.prefix) <= k:
            return 0
        return self.prefix[-1] // self.prefix[-k-1]
```

Please upvote is you found it useful!!
['Array', 'Math', 'Design', 'Data Stream', 'Prefix Sum', 'Python', 'C++', 'Java', 'Python3']