← All coding problems

Product Of The Last K Numbers

Mediumprefix-sumdesignarraymath

The problem

You need to design a data structure that accepts a stream of numbers one by one and can return the product of the last k numbers added so far.

Your data structure must support two operations:

  1. add(num): Appends the integer num to the end of the stream.
  2. getProduct(k): Returns the product of the last k numbers in the current stream.

For example, consider the following sequence of operations:

  • add(2): Stream is [2]
  • add(5): Stream is [2, 5]
  • add(4): Stream is [2, 5, 4]
  • getProduct(2): Returns 20 (5 * 4 = 20)
  • add(0): Stream is [2, 5, 4, 0]
  • add(3): Stream is [2, 5, 4, 0, 3]
  • add(6): Stream is [2, 5, 4, 0, 3, 6]
  • getProduct(2): Returns 18 (3 * 6 = 18)
  • getProduct(4): Returns 0 (0 * 3 * 6 = 0, because the window includes 0)
Product Of The Last K Numbers problem: statement and solution · CureBugs