The Product of the Last K Numbers problem asks you to design a data structure that supports adding numbers to a stream and querying the product of the last k numbers added. This design problem uses prefix products with a reset-on-zero technique. The data stream, array, math, design, and prefix sum interview pattern is the core.
Apple, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests prefix product with the edge case of zeros — which would make all subsequent products zero until the zero leaves the window. The reset trick elegantly handles this.
Prefix products with zero-reset. Maintain a prefix product list [1]. For add(num): if num == 0, reset prefix = [1] (all products involving this zero are 0 until zero leaves window). Else: append prefix[-1] * num. For getProduct(k): if k >= len(prefix), return 0 (a zero is within the last k elements). Else: return prefix[-1] / prefix[-k-1].
Stream: [3,2,0,4,5,3].
prefix[-k-1] for last k elements.Product of the Last K Numbers combines prefix products with a clever zero handling trick. The zero-reset approach is elegant: when zero is added, start fresh because any window containing that zero has product 0. The out-of-range check (k >= len(prefix)) handles this implicitly. Practice similar "sliding window aggregate" design problems: "moving maximum," "moving average," "product in sliding window."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum of Absolute Differences in a Sorted Array | Medium | Solve | |
| Range Sum Query - Immutable | Easy | Solve | |
| Sum of All Odd Length Subarrays | Easy | Solve | |
| Number of Sub-arrays With Odd Sum | Medium | Solve | |
| Continuous Subarray Sum | Medium | Solve |