Python solution. With explanation. BEATS 99%
Intuition\n Describe your first thoughts on how to solve this problem. \nMy first thought is to use a list to store the numbers that have been added, and use th
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is to use a list to store the numbers that have been added, and use the last k elements of the list to calculate the product. However, I also need to consider the case where a zero is added to the list, which would make the product of the last k elements 0.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach is to use a list to store the numbers that have been added, as well as a count of the number of zeroes that have been added, and their respective indices. When a new number is added, I will check if it is a zero and update the zero count and index accordingly. When getting the product of the last k elements, I will check if there are any zeroes in the list and if the last k elements contain any of them. If they do, I will return 0, otherwise I will return the product of the last k elements.\n# Complexity\n- Time complexity: $$O(1)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ProductOfNumbers:\n\n    def __init__(self):\n        self.numbers = [1]\n        self.zero = 0\n        self.zero_index = []\n        self.last_zero = 0\n\n    def add(self, num: int) -> None:\n        if num == 0:\n            self.zero += 1\n            self.zero_index.append(len(self.numbers))\n            self.last_zero = len(self.numbers)\n            self.numbers.append(1)\n        else:\n            self.numbers.append(self.numbers[-1] * num)\n\n    def getProduct(self, k: int) -> int:\n        if self.zero == 0:\n            return self.numbers[-1] // self.numbers[-k - 1]\n        else:\n            if len(self.numbers) - k - 1 < self.zero_index[-1]:\n                return 0\n            else:\n                return self.numbers[-1] // self.numbers[-k - 1]\n\n# Your ProductOfNumbers object will be instantiated and called as such:\n# obj = ProductOfNumbers()\n# obj.add(num)\n# param_2 = obj.getProduct(k)\n```
['Python3']