Product of the Last K Numbers - Problem
Design a data structure that efficiently handles a stream of integers and can quickly calculate the product of the last
You need to implement the
Key Challenge: The
Note: Products are guaranteed to fit in a 32-bit integer, and there will always be at least
k numbers at any time.You need to implement the
ProductOfNumbers class with these methods:ProductOfNumbers()- Initialize an empty streamadd(int num)- Append a number to the streamgetProduct(int k)- Return the product of the lastknumbers
Key Challenge: The
getProduct operation should be as fast as possible since it might be called frequently. Think about how you can precompute information to make queries efficient.Note: Products are guaranteed to fit in a 32-bit integer, and there will always be at least
k numbers when getProduct(k) is called. Input & Output
example_1.py โ Basic Operations
$
Input:
obj = ProductOfNumbers()
obj.add(3)
obj.add(0)
obj.add(2)
obj.add(5)
obj.add(4)
obj.getProduct(2)
obj.getProduct(3)
obj.getProduct(4)
โบ
Output:
20
40
0
๐ก Note:
getProduct(2) returns 5*4=20, getProduct(3) returns 2*5*4=40, getProduct(4) returns 0*2*5*4=0 due to the zero
example_2.py โ No Zeros
$
Input:
obj = ProductOfNumbers()
obj.add(1)
obj.add(2)
obj.add(3)
obj.add(4)
obj.getProduct(1)
obj.getProduct(2)
obj.getProduct(4)
โบ
Output:
4
12
24
๐ก Note:
getProduct(1) returns 4, getProduct(2) returns 3*4=12, getProduct(4) returns 1*2*3*4=24
example_3.py โ Single Element
$
Input:
obj = ProductOfNumbers()
obj.add(5)
obj.getProduct(1)
โบ
Output:
5
๐ก Note:
With only one element, getProduct(1) simply returns that element
Constraints
- 1 โค nums.length โค 4 * 104
- 1 โค k โค 4 * 104
- -109 โค nums[i] โค 109
- The product of any contiguous sequence fits in a 32-bit integer
- At most 4 * 104 calls will be made to add and getProduct
- It is guaranteed that there will be at least k numbers when getProduct(k) is called
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Start with prefix products array containing [1]
2
Add Numbers
For each new number, multiply with last prefix product
3
Query Range
Use division to get product of any range in O(1)
Key Takeaway
๐ฏ Key Insight: Prefix products transform O(k) range queries into O(1) operations using division, similar to how prefix sums work with subtraction!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code