LeetCode 1352: Product Of The Last K Numbers, explained

Compute the product of the last k numbers in a dynamic stream using a prefix product array that resets when encountering zeros.

intermediate7 min readBy sahil1678kumarReviewed by sahil1678kumar · 23 Nov 2026

The Product of the Last K Numbers problem asks us to design a data structure that ingests numbers from a stream and computes the product of the last k inserted elements on demand. It is a classic variation of the prefix product technique that tests your ability to handle zero resets cleanly in O(1) time.

The problem

We need to build a class ProductOfNumbers with two methods:

  • add(num): Appends an integer num to the running stream.
  • getProduct(k): Calculates and returns the product of the last k integers added to the stream.

For example, consider the following sequence of operations:

  1. add(4): Stream is [4]
  2. add(3): Stream is [4, 3]
  3. add(2): Stream is [4, 3, 2]
  4. getProduct(2): Returns product of last 2 elements (3 * 2 = 6)
  5. add(0): Stream is [4, 3, 2, 0]
  6. add(5): Stream is [4, 3, 2, 0, 5]
  7. add(2): Stream is [4, 3, 2, 0, 5, 2]
  8. getProduct(2): Returns product of last 2 elements (5 * 2 = 10)
  9. getProduct(4): Returns 0 because the last 4 elements [2, 0, 5, 2] include a zero.

Computing the product by iterating back k elements every time would take O(k) time. When k is up to 40,000 and there are 40,000 queries, an O(k) approach will TLE (Time Limit Exceeded). We need both operations to run in O(1) time.

The key idea

Just as prefix sums allow computing range sums in O(1) time (which you can review in our prefix sums guide), prefix products allow computing contiguous range products using division. If prefix[i] stores the product of all elements from index 0 to index i, then the product of elements in range [i, j] is:

product(i..j) = prefix[j] / prefix[i - 1]

However, division breaks when zeros enter the sequence. Dividing by zero causes arithmetic errors, and once a zero enters a product, all subsequent cumulative products become zero, destroying previous historical product data.

The key breakthrough is realizing that zero acts as a hard boundary:

  1. Any getProduct(k) query whose window spans across a zero will immediately result in 0.
  2. Any getProduct(k) query whose window sits entirely after the latest zero can ignore all numbers added before that zero.

Because of this property, whenever we encounter a 0, we can clear our prefix product list and start fresh with a clean slate [1].

When getProduct(k) is called:

  • If k is greater than or equal to the current length of our prefix array, it means the requested window reaches back to or past a zero. We instantly return 0.
  • Otherwise, the product is simply prefix[last] / prefix[last - k].

Let us trace our example step-by-step:

  • Initialize: prefix = [1]
  • add(4): prefix = [1, 4]
  • add(3): prefix = [1, 4, 12]
  • add(2): prefix = [1, 4, 12, 24]
  • getProduct(2): Array length is 4. k = 2 < 4. Result = prefix[3] / prefix[3 - 2] = 24 / 4 = 6.
  • add(0): Zero detected. Reset prefix = [1].
  • add(5): prefix = [1, 5]
  • add(2): prefix = [1, 5, 10]
  • getProduct(2): Array length is 3. k = 2 < 3. Result = prefix[2] / prefix[2 - 2] = 10 / 1 = 10.
  • getProduct(4): Array length is 3. k = 4 >= 3. Window spans past zero reset point, so return 0.

Approach

  1. Maintain a list prefix initialized with a single dummy element [1]. The dummy element simplifies boundary math so we do not need special cases for taking the product of all elements added since the last reset.
  2. In add(num):
    • If num == 0, reset prefix to [1].
    • If num != 0, calculate prefix.last * num and append it to prefix.
  3. In getProduct(k):
    • Check if k >= len(prefix).
    • If true, return 0 (the requested window includes a zero).
    • Otherwise, return prefix[len(prefix) - 1] / prefix[len(prefix) - 1 - k].

Code

class ProductOfNumbers:

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

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

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

Complexity

  • Time Complexity:
    • add(num): O(1) amortized time. Appending to dynamic arrays takes O(1) time. Resetting the array via .clear() in Java/C++ or re-assigning in Python/JS runs in O(1) amortized time.
    • getProduct(k): O(1) time. It involves a single length check and one integer division operation.
  • Space Complexity: O(N) auxiliary space, where N is the total number of calls to add since the last zero. In the worst case where no zeros are added, we store up to 40,000 elements in the prefix array.

Edge cases and common mistakes

  • Off-by-one errors in condition: A common mistake is using k > len(prefix) instead of k >= len(prefix). Because our array contains a dummy 1 at index 0, if 2 valid numbers are added after zero, len(prefix) is 3. k = 2 is valid (prefix[2] / prefix[0]), but k = 3 spans past the zero reset point, so k >= len(prefix) correctly returns 0.
  • Re-allocating list objects repeatedly: In languages like Java or C++, creating a new ArrayList() inside add(0) triggers memory allocation and garbage collection. Using prefix.clear() reuses the allocated capacity and improves runtime performance during high-volume stream operations.
  • Integer overflow assumptions: In standard real-world applications, multiplying prefix products can quickly overflow 32-bit or 64-bit integers. In this specific LeetCode problem, constraints state that the cumulative product fits in a 32-bit signed integer.

Follow-ups an interviewer may ask

1. What if stream values can lead to 64-bit integer overflow?

If elements are large and products exceed integer limits, division-based prefix products fail. We can handle this in two ways:

  • BigInteger: Use arbitrary-precision integer arithmetic (Python handles this natively; Java has BigInteger).
  • Logarithms: Convert products to sum of logarithms: log(a * b) = log(a) + log(b). Maintain a prefix sum array of log(num). To get the product, compute exp(prefix_log[last] - prefix_log[last - k]). This converts multiplication to addition and prevents overflow, though floating-point precision issues must be managed.

2. What if stream inputs contain negative numbers?

Our solution works with negative numbers without any modification. In integer division, signs are preserved correctly (for example, -12 / -3 = 4 and 12 / -3 = -4). As long as zero is handled by resetting the array, negative numbers maintain standard mathematical properties under prefix division.

3. How would you support a popLast() operation that removes the most recent number?

If no zero was removed, popLast() is simply popping the last element from prefix in O(1) time. However, if the popped element was 0, we need to restore the prefix state prior to that zero. To support this, we would maintain a stack of previous prefix arrays or track zero position checkpoints so we can roll back state cleanly.


This is LeetCode problem 1352, Product Of The Last K Numbers, explained in our own words. CureBugs is not affiliated with LeetCode.

Mock interview

Practise explaining your code out loud

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up.

  • A timed problem in a real editor, judged on hidden tests
  • Follow-up questions, like the real round
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Keep reading

All articles
Coding problems•intermediate

Product Of The Last K Numbers: solution and explanation

7 min read
Coding problems•beginner

Stone Removal Game: solution and explanation

7 min read