Super Simple Approch ✅ 🚀 | Understand in Minutes 🔥 | O(1) TC | C++ | Java | Py | Js
🚀 Approach1️⃣ Maintain a Prefix Product Array (values)
🔹 Each time a number is added: Multiply it with the last product and store it in values.
🔹 Handling 0: If
# 🚀 Approach

## 1️⃣ Maintain a Prefix Product Array (`values`)
   - 🔹 **Each time a number is added**: Multiply it with the last product and store it in `values`.
   - 🔹 **Handling `0`**: If `num == 0`, reset `values` (since all previous products become irrelevant).

## 2️⃣ Adding a Number (`add(num)`)
   - ✅ Multiply `num` with the last stored product.
   - ✅ If `num == 0`, **reset** the product and clear `values`.
   - ✅ Otherwise, store the new **prefix product** in `values`.

## 3️⃣ Querying the Last `k` Products (`getProduct(k)`)
   - ❌ **If `k` is greater than the size of `values`**, return `0` (since a `0` was encountered).
   - 🔢 **Otherwise**, compute the product efficiently:
     - 🧮 Use division:  
       - If there are at least `k` elements, return `values.back() / values[n-k-1]` to get the product.

## ✅ Key Observations:
   - 🔥 Instead of recomputing the product every time, **we leverage prefix products**.
   - ⏳ Queries are **O(1)** since we only need **division** to compute the answer.
   - 📌 `0` resets the product, ensuring we always calculate correctly.


# Complexity
- **Time complexity**:
  - `add(num)`: **O(1)** (Appending to the array or clearing it)
  - `getProduct(k)`: **O(1)** (Retrieving the result using division)

- **Space complexity**:
  - **O(n)** (Storing prefix products in `values`)


# Code
```cpp []
class ProductOfNumbers {
public:
    vector<unsigned long long> values; // Stores the prefix product of numbers
    unsigned long long product = 1;    // Keeps track of the running product
    int index = 0;                     // Tracks the count of elements added

    ProductOfNumbers() {}

    // Function to add a new number
    void add(int num) {
        index++;  
        product *= num;  

        if (num == 0) {
            values.clear(); // Reset prefix products when encountering zero
            product = 1;
        } else {
            values.push_back(product); // Store the running product
        }
    }

    // Function to get the product of the last k elements
    int getproduct(int k) {
        if (values.size() < k) {
            return 0; // If there are fewer than k elements, return 0
        }
        int pos = values.size() - k - 1; // Find the required prefix index
        unsigned long long divisor = (pos < 0) ? 1 : values[pos]; // Determine divisor for the product
        return values.back() / divisor; // Return the product of the last k elements
    }
};
```
```javascript []
class ProductOfNumbers {
    constructor() {
        this.values = []; // Stores prefix product
        this.product = 1; // Running product
    }

    // 🟢 Adds a number to the sequence
    add(num) {
        if (num === 0) {
            // 🔴 Reset array when zero appears
            this.values = [];
            this.product = 1;
        } else {
            this.product *= num; // Multiply with previous product
            this.values.push(this.product); // Store updated prefix product
        }
    }

    // 🟢 Returns the product of the last k elements
    getProduct(k) {
        if (k > this.values.length) {
            return 0; // If there are fewer than k elements, return 0
        }
        let divisor = k === this.values.length ? 1 : this.values[this.values.length - k - 1];
        return this.values[this.values.length - 1] / divisor; // Compute product using division
    }
}

```
```python []
class ProductOfNumbers:
    def __init__(self):
        self.values = []  # Stores prefix product
        self.product = 1  # Running product

    # 🟢 Adds a number to the sequence
    def add(self, num: int) -> None:
        if num == 0:
            # 🔴 Reset list when zero appears
            self.values.clear()
            self.product = 1
        else:
            self.product *= num  # Multiply with previous product
            self.values.append(self.product)  # Store updated prefix product

    # 🟢 Returns the product of the last k elements
    def getProduct(self, k: int) -> int:
        if k > len(self.values):
            return 0  # If there are fewer than k elements, return 0
        divisor = 1 if k == len(self.values) else self.values[-k-1]
        return self.values[-1] // divisor  # Compute product using division

```
```java []
import java.util.*;

class ProductOfNumbers {
    private List<Long> values; // Stores prefix product
    private long product; // Tracks the running product

    public ProductOfNumbers() {
        values = new ArrayList<>();
        product = 1; // Initial product value
    }

    // 🟢 Adds a number to the sequence
    public void add(int num) {
        if (num == 0) {
            // 🔴 Reset the list when zero appears
            values.clear();
            product = 1;
        } else {
            product *= num; // Multiply with previous product
            values.add(product); // Store updated prefix product
        }
    }

    // 🟢 Returns the product of the last k elements
    public int getProduct(int k) {
        if (k > values.size()) {
            return 0; // If there are fewer than k elements, return 0
        }
        long divisor = (k == values.size()) ? 1 : values.get(values.size() - k - 1);
        return (int) (values.get(values.size() - 1) / divisor); // Compute the product using division
    }
}

```



['Array', 'Math', 'Design', 'Data Stream', 'Prefix Sum', 'C++', 'Java', 'Python3']