Product of the Last K Numbers

medium design prefix product

Problem

Design a class that consumes a stream of integers and answers queries about the most recent numbers. add(num) appends num (0 ≤ num ≤ 100) to the stream, and getProduct(k) returns the product of the last k numbers added. Every query is guaranteed to ask about at most as many numbers as the stream currently holds, and every answer fits in a 32-bit integer.

Inputadd(3), add(0), add(2), add(5), add(4), getProduct(2), getProduct(3), getProduct(4), add(8), getProduct(2)
Output20, 40, 0, 32
getProduct(2) = 5·4 = 20 and getProduct(3) = 2·5·4 = 40; getProduct(4) reaches back across the 0, so it is 0; after add(8), getProduct(2) = 4·8 = 32.

class ProductOfNumbers:
    def __init__(self):
        self.prefix = [1]

    def add(self, num):
        if num == 0:
            self.prefix = [1]
        else:
            self.prefix.append(self.prefix[-1] * num)

    def get_product(self, k):
        if k >= len(self.prefix):
            return 0
        return self.prefix[-1] // self.prefix[-k - 1]
class ProductOfNumbers {
  constructor() {
    this.prefix = [1];
  }

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

  getProduct(k) {
    const n = this.prefix.length;
    if (k >= n) return 0;
    return this.prefix[n - 1] / this.prefix[n - 1 - k];
  }
}
class ProductOfNumbers {
    private List<Integer> prefix = new ArrayList<>(List.of(1));

    public void add(int num) {
        if (num == 0) {
            prefix = new ArrayList<>(List.of(1));
        } else {
            prefix.add(prefix.get(prefix.size() - 1) * num);
        }
    }

    public int getProduct(int k) {
        int n = prefix.size();
        if (k >= n) return 0;
        return prefix.get(n - 1) / prefix.get(n - 1 - k);
    }
}
class ProductOfNumbers {
    vector<int> prefix{1};
public:
    void add(int num) {
        if (num == 0) prefix = {1};
        else prefix.push_back(prefix.back() * num);
    }

    int getProduct(int k) {
        int n = prefix.size();
        if (k >= n) return 0;
        return prefix[n - 1] / prefix[n - 1 - k];
    }
};
Time: O(1) per operation Space: O(n)