✅ Product of the Last K Numbers | JS🔥 | beats 99%🚀 | 🚀highly optimised & easy to understand ✅
Intuition
To solve this problem efficiently, we can use prefix products instead of storing all numbers directly. Here's the approach
Approach
Maintain a list pr
# Intuition
- To solve this problem efficiently, we can use prefix products instead of storing all numbers directly. Here's the approach
# Approach
- Maintain a list prefix where prefix[i] stores the product of all numbers from the start up to the i-th index.
- If a 0 is added, reset the prefix array since any product involving zero will be zero.
- To get the product of the last k elements efficiently:
- If k exceeds the last reset due to zero, return 0.
- Otherwise, use the formula: Product= prefix[n] / prefix[n−k]
where n is the last index.
# Complexity
> **Time complexity:**
- This approach ensures that both add() and getProduct() run in O(1) time complexity.
- add(num): O(1) (appending to an array)
- getProduct(k): O(1) (single division)

> **Space complexity:**
- This solution ensures that both operations are done in constant time, making it highly efficient.
# Code
```javascript []
class ProductOfNumbers {
    constructor() {
        this.prefix = [1]; // Stores prefix products, initialized with 1.
    }

    add(num) {
        if (num === 0) {
            this.prefix = [1]; // Reset if zero is added.
        } else {
            this.prefix.push(this.prefix[this.prefix.length - 1] * num);
        }
    }

    getProduct(k) {
        if (k >= this.prefix.length) {
            return 0; // If `k` exceeds the last reset, return 0.
        }
        return this.prefix[this.prefix.length - 1] / this.prefix[this.prefix.length - 1 - k];
    }
}

```

![DALL·E 2025-01-21 10.20.30 - A realistic, soft-toned image of a kind and humble person, sitting at a desk with a gentle smile, holding a sign that says_ 'Please upvote if this hel.webp](https://assets.leetcode.com/users/images/cd3845b0-90b6-4ede-8718-143cd216d142_1739505562.6114137.webp)

['JavaScript']