Product of the Last K Numbers — LeetCode 1352 Python Solution

MediumDesignArrayMathData StreamPrefix Sum
Problem
#1352
Pattern
Prefix Sum
Reading time
4 min

The problem

Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: ProductOfNumbers() Initializes the object with an empty stream.

Example

Input
["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]
Output
[null,null,null,null,null,null,20,40,0,null,32]
Explanation
ProductOfNumbers productOfNumbers = new ProductOfNumbers();

Python solution

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

    def add(self, num: int) -> None:
        if num == 0:
            self.s = [1]
            return
        self.s.append(self.s[-1] * num)

    def getProduct(self, k: int) -> int:
        return 0 if len(self.s) <= k else self.s[-1] // self.s[-k - 1]


# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)

Complexity

MeasureComplexity
TimeO(1)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1352. Product of the Last K Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1352. Product of the Last K Numbers?
LeetCode 1352. Product of the Last K Numbers is rated Medium on LeetCode.
What is the time complexity of LeetCode 1352. Product of the Last K Numbers?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 1352. Product of the Last K Numbers?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1352. Product of the Last K Numbers cover?
LeetCode 1352. Product of the Last K Numbers is tagged Design, Array, Math, Data Stream and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview