Efficient Prefix Product Tracker with Zero Handling (JAVA) (16ms)
IntuitionThe problem requires maintaining a dynamic list of numbers and efficiently computing the product of the last k elements. A naive approach would be to i
# Intuition
The problem requires maintaining a dynamic list of numbers and efficiently computing the product of the last k elements. A naive approach would be to iterate through the last k elements every time a query is made, leading to an O(k) time complexity per query. However, this can be optimized using prefix product arrays.

To efficiently retrieve the product, we store cumulative products in a separate list (product), allowing us to compute results in O(1) time using division. However, the presence of 0s in the input breaks the prefix product chain, requiring special handling.

# Approach
Maintain two lists:

arr → Stores the original numbers for reference.
product → Stores the prefix product values (cumulative product of numbers).
Handling additions (add(num)):

If num is non-zero, multiply it with the previous product and store it.
If num is zero, reset the prefix product list and track the last zero index (zero).
Handling queries (getProduct(k)):

If k extends beyond the last zero's position → return 0 (since zero invalidates the product).
Otherwise, retrieve the product using division of prefix product values:

        product[n−1]/product[n−k−1]

This gives the product of the last k elements in O(1) time.

# Complexity
Time Complexity:

add(num): O(1) (single multiplication or reset)
getProduct(k): O(1) (single division or zero check)
Overall: O(1) per operation

Space Complexity:

We store numbers and prefix products → O(n) in the worst case.

# Code
```java []
class ProductOfNumbers {
    ArrayList<Integer> arr= new ArrayList<>();
    ArrayList<Integer> product= new ArrayList<>();
    int n=0;
    int zero=-1;
    public ProductOfNumbers() {
        
    }
    
    public void add(int num) {
        n++;
        arr.add(num);
        if(num!=0)
        {
            
            if(product.isEmpty())
            {
                product.add(num);
            }
            else
            {
                int x=product.get(n-2);
                product.add(num*x);
            }
        }
        else
        {
            zero=n-1;
            product.add(1);
        }
    }
    
    public int getProduct(int k) {
        if(k>=(n-zero))
        {
            return 0;
        }
        else if(k==n)
        {
            return product.get(n-1);
        } 
        
        else
        {
            int prod=(product.get(n-1)/product.get(n-k-1));
            return prod;
        }
    }
}

```
['Java']