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 k numbers at any time.

You need to implement the ProductOfNumbers class with these methods:
  • ProductOfNumbers() - Initialize an empty stream
  • add(int num) - Append a number to the stream
  • getProduct(int k) - Return the product of the last k numbers

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
Prefix Products: The Key to O(1) QueriesStream of Numbers:3254Prefix Products:13630120getProduct(2) QueryWant product of last 2 numbers: [5, 4]Result = prefix[4] รท prefix[2] = 120 รท 6 = 20 โœ“Why This Worksprefix[i] = product of first i numbersRange product = total รท before_range
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!
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen