Skip to content

1352. Product of the Last K Numbers #1313

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to design a class that efficiently handles a stream of integers and can quickly return the product of the last k integers. The challenge is to ensure that both the addition of numbers and the retrieval of the product are done efficiently, even with a large number of operations.

Approach

The key insight is to use prefix products to efficiently compute the product of the last k elements. Here's the detailed approach:

  1. Prefix Products Array: Maintain an array where each element at index i represents the product of all numbers added after the last zero up to the i-th element. This array starts with an initial value of 1 to handle the base case.

  2. Handling Zeros: When a zero is added …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Feb 14, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants