O(1) solution for each operation using prefix products
IntuitionThis problem requires an efficient way to compute the product of the last k elements of a dynamically growing sequence. Using a naive approach of stori
# Intuition
This problem requires an efficient way to compute the product of the last `k` elements of a dynamically growing sequence. Using a naive approach of storing all elements and calculating the product iteratively would be inefficient. Instead, maintaining a **prefix product** array allows us to compute the result in constant time.

# Approach
1. **Maintain a prefix product array**: Instead of storing all elements, we store their cumulative product.
2. **Handling Zero**:
   - If `0` is added, all previous values become irrelevant since any product involving `0` is `0`.
   - Reset the prefix product array to `[1]`.
3. **Querying**:
   - If `k >= prefix.size()`, it means we encountered a `0`, so return `0`.
   - Otherwise, the result is computed as `prefix.back() / prefix[n - 1 - k]`.

# Complexity
- **Time Complexity**:
  - `add(num)`: $$O(1)$$ (Appending to the prefix array)
  - `getProduct(k)`: $$O(1)$$ (Using division to compute the result)

- **Space Complexity**:
  - $$O(n)$$ (Storing prefix products)


# Code

```cpp []
class ProductOfNumbers {
private:
    vector<int> prefix; 

public:
    ProductOfNumbers() {
        prefix.push_back(1); 
    }

    void add(int num) {
        if (num == 0) {
            // If 0 is added, reset the prefix product list
            prefix.clear();
            prefix.push_back(1);
        } else {
            prefix.push_back(num * prefix.back());
        }
    }

    int getProduct(int k) {
        int n = prefix.size();
        if (k >= n) {
            return 0; // If k is greater than available elements after a reset
        }
        return prefix.back() / prefix[n - 1 - k];
    }
};

/**
 * Your ProductOfNumbers object will be instantiated and called as follows:
 * ProductOfNumbers* obj = new ProductOfNumbers();
 * obj->add(num);
 * int param_2 = obj->getProduct(k);
 */
```
```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(num * prefix.get(prefix.size() - 1));
        }
    }

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

/**
 * Your ProductOfNumbers object will be instantiated and called as follows:
 * ProductOfNumbers obj = new ProductOfNumbers();
 * obj.add(num);
 * int param_2 = obj.getProduct(k);
 */
```

['Array', 'Prefix Sum', 'C++', 'Java']