Intuition
Keep the running product after every number since the latest zero. The product of the last k numbers is the newest running product divided by the one k places earlier, or 0 if the last k reach back past that zero.
Explanation
Why not multiply on every question
Multiplying the last k numbers each time costs O(k) per question. With tens of thousands of questions that is far too much repeated work, because neighbouring questions multiply mostly the same numbers.
Keep running products
Keep a list prefix, where each entry is the product of every number so far. Start it with 1, which stands for "no numbers yet".
add(num): prefix.append(prefix[-1] * num)
The product of the last k numbers is the newest running product divided by the one k places earlier. The numbers before the last k are factors of both, so the division cancels them:
getProduct(k) = prefix[-1] // prefix[-1 - k]
The 1 at the front means that asking for every number needs no special case.
What about zero?
A zero would turn every later running product into 0, and dividing by 0 is not allowed. So when a zero arrives, restart the list as [1].
After that, prefix holds one entry for each number since the latest zero, plus the leading 1. If k is larger than the count of those numbers, the last k numbers must include the zero, so the answer is 0.
Worked example
| Call | prefix afterwards | Returned |
|---|---|---|
add(3) | [1, 3] | |
add(0) | [1] (restart) | |
add(2) | [1, 2] | |
add(5) | [1, 2, 10] | |
add(4) | [1, 2, 10, 40] | |
getProduct(2) | unchanged | 40 / 2 = 20 |
getProduct(3) | unchanged | 40 / 1 = 40 |
getProduct(4) | unchanged | only 3 numbers since the zero, so 0 |
add(8) | [1, 2, 10, 40, 320] | |
getProduct(2) | unchanged | 320 / 10 = 32 |
Complexity
- Time: O(1) for each
addand eachgetProduct. - Space: O(n), one running product per number since the latest zero.
Implementation
import java.util.ArrayList;
import java.util.List;
class ProductOfNumbers {
private final List<Integer> prefix = new ArrayList<>();
public ProductOfNumbers() {
prefix.add(1);
}
public void add(int num) {
if (num == 0) {
prefix.clear();
prefix.add(1);
} else {
prefix.add(prefix.get(prefix.size() - 1) * num);
}
}
public int getProduct(int k) {
int last = prefix.size() - 1;
if (k > last) {
return 0;
}
return prefix.get(last) / prefix.get(last - k);
}
}