Leetcode 1352: Product of the Last K Numbers

grid47
grid47
Exploring patterns and algorithms
Jun 24, 2024 5 min read

Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers in the stream.
Problem
Approach
Steps
Complexity
Input: The input consists of a sequence of operations: initialize the object, add numbers to the stream, and get the product of the last k numbers.
Example: For example, ['ProductOfNumbers', 'add', 'add', 'add', 'getProduct'] with input [[], [3], [0], [2], 2].
Constraints:
• 0 <= num <= 100
• 1 <= k <= 4 * 10^4
• At most 4 * 10^4 calls to add and getProduct.
Output: The output should be a list of integers where each element is the result of the respective 'getProduct' operation.
Example: For example, ['getProduct(2)', 'getProduct(3)'] could return 20 and 40, respectively.
Constraints:
• The result will always fit in a 32-bit integer.
Goal: Design an efficient system to keep track of the last k numbers and compute their product.
Steps:
• 1. Use a list to keep track of the products of the numbers in the stream.
• 2. If a zero is encountered, reset the product history.
• 3. For each getProduct query, compute the product of the last k numbers.
Goal: The solution should handle up to 4 * 10^4 operations efficiently.
Steps:
• The product at any point should fit within a 32-bit integer.
Assumptions:
• The input list has at least k numbers when calling 'getProduct'.
• Any sequence of numbers in the list fits within the range of a 32-bit integer.
Input: Example 1: ['ProductOfNumbers', 'add', 'add', 'add', 'add', 'add', 'getProduct(2)', 'getProduct(3)', 'getProduct(4)', 'add', 'getProduct(2)']
Explanation: The operations add numbers to the stream, and getProduct computes the product of the last k numbers.

Input: Example 2: ['ProductOfNumbers', 'add', 'add', 'add', 'getProduct(3)']
Explanation: After adding numbers [1, 2, 3], the product of the last 3 numbers is 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus