Similar Problems

Similar Problems not available

Product Of The Last K Numbers - Leetcode Solution

LeetCode:  Product Of The Last K Numbers Leetcode Solution

Difficulty: Medium

Topics: math design array  

Problem Statement:

Design an algorithm that takes a stream of integers as input and returns the product of the last k integers in the stream.

Example:

Input: stream of integers: [3, 5, 2, 6] k = 3

Output: Product of the last k integers: 60

Explanation: The last 3 integers in the stream are 5, 2, and 6, and their product is 60.

Solution Approach:

To solve this problem, we can make use of a sliding window approach. We maintain a product variable that keeps track of the product of the last k integers received in the stream. Whenever a new integer is received in the stream, we multiply it with this product variable. At the same time, we remove the first integer from the product variable (the integer that is no longer a part of the last k integers in the stream).

If at any point, the stream contains less than k integers, we return 0 as the product of the last k integers is undefined.

Steps:

  1. Initialize a product variable to 1, representing the product of the last k integers in the stream. Initialize a list to store the last k integers received in the stream.

  2. For each new integer received in the stream, multiply it with the product variable and update the product variable accordingly.

  3. Append the new integer to the list of the last k integers received in the stream.

  4. If the length of the list is greater than k, remove the first integer from the list and update the product variable accordingly.

  5. Return the product of the k integers in the list as the final result.

Code Implementation:

Here's an implementation of the above approach in Python:

class ProductOfLastK: def init(self, k): self.k = k self.product = 1 self.last_k_ints = []

def add(self, num):
    self.product *= num
    self.last_k_ints.append(num)

    # If the length of the list is greater than k, remove the first integer and update the product variable
    if len(self.last_k_ints) > self.k:
        self.product /= self.last_k_ints.pop(0)

def getProduct(self):
    # If the length of the list is less than k, the product is undefined
    if len(self.last_k_ints) < self.k:
        return 0
    
    return self.product

Example usage

p = ProductOfLastK(3) p.add(3) p.add(5) p.add(2)

print(p.getProduct()) # Output: 30

p.add(6) print(p.getProduct()) # Output: 60

p.add(0) print(p.getProduct()) # Output: 0

p.add(9) print(p.getProduct()) # Output: 0 (only last 3 numbers are considered in the product)

Product Of The Last K Numbers Solution Code

1