Product of the Last K Numbers - Problem
Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.
Implement the ProductOfNumbers class:
ProductOfNumbers()- Initializes the object with an empty stream.void add(int num)- Appends the integer num to the stream.int getProduct(int k)- Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["ProductOfNumbers", "add", "add", "getProduct"], values = [null, 2, 3, 2]
›
Output:
[null, null, null, 6]
💡 Note:
Initialize object, add 2, add 3, then getProduct(2) returns 2 × 3 = 6
Example 2 — Multiple Queries
$
Input:
operations = ["ProductOfNumbers", "add", "add", "add", "getProduct", "getProduct"], values = [null, 3, 0, 2, 2, 3]
›
Output:
[null, null, null, null, 0, 0]
💡 Note:
After adding [3, 0, 2], getProduct(2) = 0 × 2 = 0, getProduct(3) = 3 × 0 × 2 = 0
Example 3 — Single Element
$
Input:
operations = ["ProductOfNumbers", "add", "getProduct"], values = [null, 5, 1]
›
Output:
[null, null, 5]
💡 Note:
Add single element 5, then getProduct(1) returns just that element: 5
Constraints
- 1 ≤ operations.length ≤ 1000
- -100 ≤ num ≤ 100
- 1 ≤ k ≤ current stream length
- At most 1000 calls total to add and getProduct
Visualization
Tap to expand
Understanding the Visualization
1
Stream Input
Numbers arrive one by one: 2, 3, 2, 3
2
Query Processing
getProduct(k) needs product of last k numbers
3
Efficient Result
Return product quickly using precomputed data
Key Takeaway
🎯 Key Insight: Prefix products enable O(1) range queries by storing cumulative products
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code