Product of the Last K Numbers

Design ProductOfNumbers, which receives a stream of integers. add(num) appends num to the stream, and getProduct(k) returns the product of the last k numbers added. You may assume the stream always holds at least k numbers and that every answer fits in a 32-bit integer.

30:00

Product of the Last K Numbers
medium
Free written solution
Topics
Companies

Design ProductOfNumbers, which receives a stream of integers. add(num) appends num to the stream, and getProduct(k) returns the product of the last k numbers added. You may assume the stream always holds at least k numbers and that every answer fits in a 32-bit integer.

Example 1:
Input: {"commands":["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"],"values":[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]}
Output: [null,null,null,null,null,null,20,40,0,null,32]
Constraints:
  • 0≤num≤1000 \leq \text{num} \leq 100

  • 1≤k≤4×1041 \leq k \leq 4 \times 10^4

  • At most 4×1044 \times 10^4 calls are made to add and getProduct.

  • The product of the stream at any point fits in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"],"values":[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]}
new
add(3)
add(0)
add(2)
add(5)
add(4)
getProduct(2)
getProduct(3)
getProduct(4)

…

Store prefix products of the numbers added since the last zero, starting from a 1. Any suffix product is then one division.

stream (top) and prefix products (bottom)

start
1

no numbers yet

0 = wall: prefixes restart at 1 under it

green = prefix[-1]

pink = divisor prefix[-1-k]

Returned values

[]
Variables
VariableValue
prefix[1]
DepthFunction Call
Stack empty
0/12