Leetcode Problem 1352. Product of the Last K Numbers

1352. Product of the Last K Numbers

Leetcode Solutions

Prefix Product with Stream Handling

  1. Initialize an empty list prefix_products with a single element [1] to handle the neutral element of multiplication.
  2. When add is called with a number num:
    • If num is not zero, multiply num with the last element in prefix_products and append the result to prefix_products.
    • If num is zero, reset prefix_products to [1].
  3. When getProduct is called with an integer k:
    • If k is larger than the current size of prefix_products, return 0.
    • Otherwise, return the result of dividing the last element in prefix_products by the element at the position size - k - 1.
UML Thumbnail

Brute Force Product Calculation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...