100% Beats | 10ms | PHP & Go
Approach
Instead of recalculating the product every time (O(k)), we store cumulative products.
Division allows instant retrieval in O(1).
Complexity
Add(num) →

# Approach
<!-- Describe your approach to solving the problem. -->
- Instead of recalculating the product every time (O(k)), we store cumulative products.
- Division allows instant retrieval in O(1).

# Complexity
- Add(num) → O(1) (Appending and multiplying last element)
- GetProduct(k) → O(1) (Using division)


# Code
```php []
class ProductOfNumbers {
    private array $prefixProducts;
    /**
     */
    function __construct() {
        $this->prefixProducts = [1]; // 1 acts as a dummy prefix
    }
  
    /**
     * @param Integer $num
     * @return NULL
     */
    function add($num) {
        if ($num == 0) {
            $this->prefixProducts = [1]; // Reset the prefix array on zero
        } else {
            $this->prefixProducts[] = end($this->prefixProducts) * $num;
        }
    }
  
    /**
     * @param Integer $k
     * @return Integer
     */
    function getProduct($k) {
        $n = count($this->prefixProducts);
        if ($k >= $n) return 0; // If k exceeds valid range due to zero reset, return 0
        return (int) ($this->prefixProducts[$n - 1] / $this->prefixProducts[$n - 1 - $k]);
    }
}

/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * $obj = ProductOfNumbers();
 * $obj->add($num);
 * $ret_2 = $obj->getProduct($k);
 */
```
```golang []
type ProductOfNumbers struct {
    prefixProducts []int
}


func Constructor() ProductOfNumbers {
    return ProductOfNumbers{prefixProducts: []int{1}} // Dummy prefix
}


func (this *ProductOfNumbers) Add(num int)  {
    if num == 0 {
        this.prefixProducts = []int{1} // Reset prefix array on zero
    } else {
        last := this.prefixProducts[len(this.prefixProducts)-1]
        this.prefixProducts = append(this.prefixProducts, last*num)
    }
}


func (this *ProductOfNumbers) GetProduct(k int) int {
    n := len(this.prefixProducts)
    if k >= n {
        return 0 // If k exceeds valid range due to zero reset, return 0
    }
    return this.prefixProducts[n-1] / this.prefixProducts[n-1-k]
}


/**
 * Your ProductOfNumbers object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Add(num);
 * param_2 := obj.GetProduct(k);
 */
```
['PHP', 'Go']