---
tags: leetcode
---
# [1352. Product of the Last K Numbers](https://leetcode.com/problems/product-of-the-last-k-numbers/)
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
class ProductOfNumbers {
public:
ProductOfNumbers() {
startIdx = prefixProduct.size();
prefixProduct.push_back(1);
}
void add(int num) {
if (num == 0) {
startIdx = prefixProduct.size();
prefixProduct.push_back(1);
return;
}
prefixProduct.push_back(prefixProduct.back() * num);
}
int getProduct(int k) {
int idx = prefixProduct.size() - 1 - k;
if (idx >= startIdx) {
return prefixProduct.back() / prefixProduct[idx];
}
return 0;
}
private:
vector<int> prefixProduct;
int startIdx;
};
/**
* Your ProductOfNumbers object will be instantiated and called as such:
* ProductOfNumbers* obj = new ProductOfNumbers();
* obj->add(num);
* int param_2 = obj->getProduct(k);
*/
```
### Time Complexity
* ProductOfNumbers: O(1)
* add: O(1)
* getProduct: O(1)
### Space Complexity
* ProductOfNumbers: O(1)
* add: O(1)
* getProduct: O(1)
# Miscellaneous
<!--
# Test Cases
```
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]
```
* Time Limit Exceeded
https://leetcode.com/problems/product-of-the-last-k-numbers/submissions/839202062/
-->