Product of the Last K Numbers
Problem
Design a data structure over a stream of integers supporting add(num) and getProduct(k) — the product of the last k numbers added. Zeros must be handled correctly.
Input / Output
add(num): appendnumto the stream.getProduct(k): return the product of the last k added values.- Output: the product for each
getProductcall.
Constraints
- Up to 4·10^4 operations;
getProductmust be O(1) (recomputing the window per query is the naive answer). - Values may include zero.
Example
- add 3, add 0, add 2, add 5, add 4 →
getProduct(2)= 20,getProduct(3)= 40,getProduct(4)= 0 (window includes the 0).
asked …