Product Of The Last K Numbers: solution and explanation

Compute the product of the last k stream elements in O(1) time by maintaining prefix products and resetting the prefix array whenever a zero is added.

intermediate7 min readBy sahil1678kumarReviewed by sahil1678kumar · 23 Nov 2026

Range queries on arrays often rely on prefix sums to achieve O(1) performance, but prefix products can solve continuous multiplication problems using the exact same principle. This question tests your ability to adapt standard patterns to handle edge cases like zero, which breaks standard mathematical division.

The problem

You need to design a data structure that accepts a stream of numbers one by one and can return the product of the last k numbers added so far.

Your data structure must support two operations:

  1. add(num): Appends the integer num to the end of the stream.
  2. getProduct(k): Returns the product of the last k numbers in the current stream.

For example, consider the following sequence of operations:

  • add(2): Stream is [2]
  • add(5): Stream is [2, 5]
  • add(4): Stream is [2, 5, 4]
  • getProduct(2): Returns 20 (5 * 4 = 20)
  • add(0): Stream is [2, 5, 4, 0]
  • add(3): Stream is [2, 5, 4, 0, 3]
  • add(6): Stream is [2, 5, 4, 0, 3, 6]
  • getProduct(2): Returns 18 (3 * 6 = 18)
  • getProduct(4): Returns 0 (0 * 3 * 6 = 0, because the window includes 0)

The key idea

If all numbers were strictly positive, we could use a running prefix product array, similar to how prefix sums work in /learn/prefix-sums-and-hashing. If prefix[i] stores the product of all elements from index 0 to i, the product of the subarray from index i to j is simply prefix[j] / prefix[i - 1].

However, 0 creates a massive issue. Division by zero is undefined. Once a zero enters the prefix array, every subsequent prefix product becomes zero, making division impossible.

The breakthrough comes from realizing how zero impacts queries:

  1. Any product range that includes a 0 will immediately evaluate to 0.
  2. Any query for k numbers that does not include the 0 only cares about the numbers added after that 0.

This means when a 0 is added, all previously stored numbers become irrelevant for future non-zero range queries. We can clear our prefix product array completely and restart it from 1.

Let's trace how getProduct(k) works with this reset mechanism:

  • Maintain a prefix array initialized with [1].
  • When add(num) receives a non-zero number, we append prefix[-1] * num.
  • When add(0) occurs, we wipe the prefix array back to [1].
  • When getProduct(k) is called:
    • If k is less than the current length of prefix, it means all k elements were added after the last zero. The answer is prefix[-1] / prefix[-1 - k].
    • If k is greater than or equal to the length of prefix, it means the query range spans across the last zero (or goes beyond available non-zero elements). The answer must be 0.

Step-by-step trace

Let's walk through our example using prefix = [1]:

  1. add(2): prefix becomes [1, 2].
  2. add(5): prefix becomes [1, 2, 10].
  3. add(4): prefix becomes [1, 2, 10, 40].
  4. getProduct(2): k = 2. Length of prefix is 4. Since 2 < 4, calculate prefix[3] / prefix[3 - 2] = 40 / prefix[1] = 40 / 2 = 20.
  5. add(0): Number is 0. Reset prefix to [1].
  6. add(3): prefix becomes [1, 3].
  7. add(6): prefix becomes [1, 3, 18].
  8. getProduct(2): k = 2. Length of prefix is 3. Since 2 < 3, calculate prefix[2] / prefix[2 - 2] = 18 / prefix[0] = 18 / 1 = 18.
  9. getProduct(4): k = 4. Length of prefix is 3. Since 4 >= 3, the window includes a zero, so return 0.

Approach

  1. Initialization: Create an array prefix containing a single dummy element 1. This dummy element simplifies calculations when k equals the entire count of non-zero elements added since the last zero.
  2. Add Operation (add(num)):
    • Check if num == 0.
    • If num is 0, reset prefix to [1].
    • If num is non-zero, take the last element in prefix, multiply it by num, and append it to prefix.
  3. Get Product Operation (getProduct(k)):
    • Compare k with the size of prefix minus 1 (or check if k >= len(prefix)).
    • If k >= len(prefix), return 0 because the requested window contains at least one 0.
    • Otherwise, return 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) time. Dynamic array append operations take amortized O(1) time. Resetting the array is also O(1) time when reallocating or clearing.
    • getProduct(k): O(1) time. Array lookup and single integer division take O(1) time.
  • Space Complexity: O(N) auxiliary space, where N is the number of elements added since the last zero. In the worst case with no zeros, prefix stores up to N elements.

Edge cases and common mistakes

  • Zeros in stream: Failing to clear the prefix product array when encountering 0 will cause division by zero errors or corrupted results.
  • Off-by-one errors in indexing: Putting dummy 1 at index 0 ensures that asking for k elements when len(prefix) == k + 1 correctly divides by prefix[0] (which is 1).
  • Querying exact count of non-zero elements: If prefix has size 4 (meaning 3 numbers were added), and k = 3, k < 4 is true, so we compute prefix[3] / prefix[0]. Make sure your condition correctly checks k >= len(prefix) to return 0.

Follow-ups an interviewer may ask

1. What if the stream contains negative numbers?

Negative numbers do not break prefix products because mathematical division handles signs naturally (-a / -b = a / b, +a / -b = -c). The exact same algorithm works without any modifications.

2. What if numbers can be large and cause 32-bit integer overflow?

If constraints allowed large values, standard integers would overflow. You could:

  • Use 64-bit integers (long in Java/C++) or arbitrary precision integers (BigInt in JavaScript, default int in Python).
  • Store prime factorizations if queries require modular arithmetic.
  • Store log values and use exponentiation, though floating-point precision issues may arise.

3. Can we implement this structure with O(1) extra space?

If queries can request any arbitrary k up to the total stream size, storing past elements is mathematically necessary. You cannot achieve O(1) auxiliary space without restricting k or storing stream elements.

4. What if we need to support updates or deletions of historical stream elements?

If elements in the middle of the stream can change, a prefix array requires O(N) time to update. In that scenario, use a Segment Tree or Binary Indexed Tree (Fenwick Tree) to support both updates and range product queries in O(log N) time.

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•beginner

Stone Removal Game: solution and explanation

7 min read
Coding problems•intermediate

LeetCode 1352: Product Of The Last K Numbers, explained

7 min read
DSA patterns•intermediate

Prefix sums and hashing

11 min read