Product of the Last K Numbers

MediumDesignprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Integers are appended to a stream one by one. At any point you may be asked for the product of the most recent k integers. Implement: - ProductOfNumbers() starts with an empty stream. - add(num) appends num to the stream. - getProduct(k) returns the product of the last k numbers in the stream. getProduct(k) is only called when the stream holds at least k numbers, and its answer is guaranteed to fit in a signed 32-bit integer. Note that num can be 0. Both operations should be O(1) (amortized).

Examples

Input: ["ProductOfNumbers","add","add","getProduct","add","add","add","getProduct","getProduct","add","getProduct"] [[],[2],[5],[2],[0],[3],[4],[2],[3],[1],[3]]
Output: [null,null,null,10,null,null,null,12,0,null,12]
2 × 5 = 10. After [2,5,0,3,4]: the last two give 12, and the last three include the 0. After adding 1, the last three are 3 × 4 × 1 = 12.
Input: ["ProductOfNumbers","add","getProduct","add","getProduct"] [[],[7],[1],[1],[2]]
Output: [null,null,7,null,7]
The last number is 7, and 7 × 1 = 7.

Constraints

  • 0 <= num <= 100
  • 1 <= k <= 4 * 10^4
  • At most 4 * 10^4 calls in total.
  • The stream holds at least `k` numbers when `getProduct(k)` is called.
  • Every answer fits in a 32-bit signed integer.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems