"Optimized Prefix Product Array: Fast Queries with Constant Time Complexity" 🚀 . Easy Java Solution
Intuition
Instead of storing all elements, we store their cumulative product, allowing quick product queries.
If 0 is added, we reset the list since any product
# Intuition
- Instead of storing all elements, we store their cumulative product, allowing quick product queries.
- If 0 is added, we reset the list since any product including 0 is 0.

# Approach

- Initialization:
    - Maintain a list nums that stores prefix products.
    - Start with 1 to facilitate multiplication.
     
- Adding a Number (add method):- 
    - If num == 0, reset the list.
    - Otherwise, append nums[last] * num to maintain prefix product.
    
- Querying the Product (getProduct method): - 
    - If k >= nums.size(), return 0 (means a 0 was encountered).

​


# Complexity
- Time complexity: O(1)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class ProductOfNumbers {

    ArrayList<Integer> nums;

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

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

    public int getProduct(int k) {

        int size = nums.size();
        if (k >= size) return 0; 
        return nums.get(size - 1) / nums.get(size - 1 - k);
    }
}
```
['Java']