Python | Prefix Product | Simple Solution With Explanation
Logic:\n1. Initialize an array with value 1 and is used to store the prefix product.\n2. Whenever a new number is added, append the prefix with (prefix[-1] x nu
## Logic:\n1. Initialize an array with value 1 and is used to store the prefix product.\n2. Whenever a new number is added, append the **prefix** with **(prefix[-1] x num)**\n3. Product of last k numbers would be **(prefix[-1] // prefix[-1-k])**\n\nThe above algorithm will work fine iff **0** is never encountered.\nTo accommodate **0** also, we need to slightly tweak the algorithm.\nLet us say that whenever **0** is encountered, **prefix** reinitialize with **[1]** and again prefix product is calculated for next numbers.\nAnd now when the prod of last k elements is needed, we can check whether the length of prefix is greater than or equal to k. \n - If it is then the above formula will work to get the product.\n - Else, simply return **0** because there must be atleast one 0 in last k elements and that is why the length of prefix is less than k.\n\n\n```\nclass ProductOfNumbers:\n\n    def __init__(self):\n        self.prefix = [1]\n\n    def add(self, num: int) -> None:\n        if num == 0:\n            self.prefix = [1]\n        else:\n            self.prefix.append(self.prefix[-1] * num)\n\n    def getProduct(self, k: int) -> int:\n        if k >= len(self.prefix):\n            return 0\n\n        return self.prefix[-1] // self.prefix[-1 - k]\n\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# nums = [1,2,3,4,5]\n# prod = [1,1,2,6,24,120]\n# last 2\n```\n\n***If you liked the above solution then please upvote!***
['Python']