Both GetProduct and Add O(1). Beats 100.00%
ApproachStore the product of numbers in an array. To get the number, divide the last number by the one in position k - 1 from the end. To avoid unnecessary if w
# Approach
Store the product of numbers in an array. To get the number, divide the last number by the one in position `k - 1` from the end. To avoid unnecessary `if` when there is only one number in the array, add `1` to the array.

![1.png](https://assets.leetcode.com/users/images/eb3ec9c8-fcc2-4c95-b6d8-d15e4a7339e1_1739503463.7491596.png)

![2.png](https://assets.leetcode.com/users/images/dddd4a09-3e50-4b83-a0b3-3032712567ba_1739503473.70323.png)

![3.png](https://assets.leetcode.com/users/images/dc1cbf2e-cd03-44ab-83e6-85c24735d6a2_1739503977.7571275.png)


# Complexity
- Time complexity: $$O(n)$$, both `GetProduct` and `Add` in $$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
```javascript []
class ProductOfNumbers {
    a = [1];

    add(x) {
        if (x !== 0) this.a.push(x * this.a.at(-1));
        else this.a = [1]; // faster then this.a.length = 1;
    }

    getProduct(k) {
        return k < this.a.length ? this.a.at(-1) / this.a.at(-k - 1) : 0;
    }
}
```
```cpp []
class ProductOfNumbers {
    vector<int> a{1};

public:
    void add(int x) {
        if (x != 0) {
            a.push_back(x * a.back());
        } else {
            a.clear();
            a.push_back(1);
        }
    }

    int getProduct(int k) {
        return k < a.size() ? a.back() / a[a.size() - k - 1] : 0;
    }
};
```
```java []
class ProductOfNumbers {
    private ArrayList<Integer> a;

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

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

    public int getProduct(int k) {
        return k < a.size() ? a.get(a.size() - 1) / a.get(a.size() - k - 1) : 0;
    }
}
```
```python3 []
class ProductOfNumbers:
    def __init__(self):
        self.a = [1]

    def add(self, x: int) -> None:
        if x != 0:
            self.a.append(x * self.a[-1])
        else:
            self.a = [1]

    def getProduct(self, k: int) -> int:
        return self.a[-1] // self.a[-k - 1] if k < len(self.a) else 0
```
['Math', 'Design', 'Data Stream', 'Prefix Sum', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript']