Skip to content

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.

Medium#1352
LeetCode Problem

Product of the Last K Numbers

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

Input
["ProductOfNumbers","add","add","add","add","getProduct","getProduct","add","getProduct"]
[[],[2],[0],[3],[4],[2],[3],[5],[2]]
Output
[null,null,null,null,null,12,0,null,20]
Explanation

The latest two entries first multiply to 12; the latest three include zero. After adding 5, the latest two multiply to 20.

Constraints

0 <= num <= 100
1 <= k <= 4 * 10^4
At most 4 * 10^4 total calls to add and getProduct.
Requested k never exceeds the stream length.
Contiguous products fit in a signed 32-bit integer.

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.