Practice Product of the Last K Numbers
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Problem Statement
ProductOfNumbers starts with an empty stream. add(num) appends an integer, and getProduct(k) returns the product of its most recent k entries. Queries always have at least k entries available. Products of contiguous sequences fit in a signed 32-bit integer. Practice approach: Keep prefix products for the suffix after the latest zero, starting with 1. On zero, reset that suffix. A query extending past it returns zero; otherwise divide the last prefix product by the one k positions earlier. Each operation is O(1) with O(n) retained-prefix storage. Resetting is essential because division by a zero prefix is invalid.
Source: Product of the Last K Numbers on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
["ProductOfNumbers","add","add","add","add","getProduct","getProduct","add","getProduct"] [[],[2],[0],[3],[4],[2],[3],[5],[2]]
[null,null,null,null,null,12,0,null,20]
The latest two entries first multiply to 12; the latest three include zero. After adding 5, the latest two multiply to 20.
Constraints
Related LeetCode Problems
Practice more problems similar to Product of the Last K Numbers.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.