Product of the Last K Numbers (LeetCode 1352): Solution and Explanation

Medium
Array
Math
Design
Data Stream
Prefix Sum

Design a stream that supports add(num) and getProduct(k), the product of the last k numbers, both in constant time.

Intuition

Multiplying the last k numbers on every query costs O(k), which is too slow when there are tens of thousands of calls.

Prefix sums answer any range sum with one subtraction. Prefix products do the same with one division: if prefix[i] is the product of the first i numbers, the last k numbers multiply to prefix[-1] / prefix[-1-k].

The only thing that breaks division is a zero. But a zero also makes every product that reaches back past it equal to 0, so the history before it is useless. Throw it away and restart the prefix list at 1.

Approach: Prefix products with reset on zero

  1. Start with prefix = [1], the empty product.
  2. add(num): if num is 0, reset prefix to [1]. Otherwise append prefix[-1] * num.
  3. getProduct(k): if k >= len(prefix), fewer than k numbers have arrived since the last 0, so the window contains that 0. Return 0.
  4. Otherwise return prefix[-1] / prefix[-1 - k].

Step-by-step example

add 3, 0, 2, 5, 4; getProduct 2, 3, 4; add 8; getProduct 2
  1. add(3): prefix = [1, 3]. add(0): reset, prefix = [1].
  2. add(2), add(5), add(4): prefix = [1, 2, 10, 40].
  3. getProduct(2) = 40 / prefix[1] = 40 / 2 = 20. getProduct(3) = 40 / 1 = 40.
  4. getProduct(4): 4 >= len(prefix) = 4, so the window reaches the 0. Return 0.
  5. add(8): prefix = [1, 2, 10, 40, 320]. getProduct(2) = 320 / 10 = 32.

Code: Python, Java, C++

1class ProductOfNumbers:
2    def __init__(self):
3        self.prefix = [1]
4
5    def add(self, num: int) -> None:
6        if num == 0:
7            self.prefix = [1]
8        else:
9            self.prefix.append(self.prefix[-1] * num)
10
11    def getProduct(self, k: int) -> int:
12        if k >= len(self.prefix):
13            return 0
14        return self.prefix[-1] // self.prefix[-1 - k]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Prefix products with reset on zero O(1) per call
Track the last zero position O(1) per call
Multiply on demand O(k) per query
Time

O(1) per call

add appends one value or resets the list, and getProduct does one comparison and one division.

Space

O(n)

The prefix list holds at most one entry per number added since the last zero.

Other approaches

Multiply on demand (time O(k) per query, space O(n))

Store the raw stream and multiply the last k values on each query. Simple, but getProduct costs O(k).

Track the last zero position (time O(1) per call, space O(n))

Keep one global prefix list where zeros are skipped, plus the index of the last zero. Equivalent, but the reset version is shorter.

Common mistakes

  • Appending 0 to the prefix list. Every later prefix becomes 0 and the division turns into 0 / 0.
  • Off-by-one on the zero check. The list has len(prefix) - 1 real numbers, so k numbers fit only when k < len(prefix).
  • Storing prefixes in a 32-bit int. A single product fits, but a prefix of many numbers can be larger than any one answer, so use 64-bit values in typed languages.

Frequently asked questions

Why is the division always exact?

prefix[-1] is prefix[-1-k] multiplied by the last k numbers, none of which is 0, so the quotient is exactly their product.

Why can the old prefixes be discarded on a zero?

Any window that reaches back past the zero includes it, so its product is 0 no matter what came before. The only information needed is how many numbers came after the zero, and that is the length of the new list.

Can prefix products overflow?

In principle a long run of numbers above 1 makes prefixes larger than any single answer. Using 64-bit integers covers the test data; Python integers never overflow.