Skip to main content
Back to problems
#1352
Medium Algorithms

Product of the last k numbers

Array Math Design Data Stream Prefix Sum
62.9% acceptance
Feb 23, 2026
2152
107
Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream. Implement the ProductOfNumbers class: ProductOfNumbers() Initializes the object with an empty stream. void add(int num) Appends the integer num to the stream. int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers. The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
pub struct ProductOfNumbers {
  prefix: Vec<i64>,
}

impl ProductOfNumbers {
  pub fn new() -> Self {
    ProductOfNumbers { prefix: vec![1] }
  }

  pub fn add(&mut self, num: i32) {
    if num == 0 {
      self.prefix = vec![1];
    } else {
      let last = *self.prefix.last().unwrap();
      self.prefix.push(last * num as i64);
    }
  }

  pub fn get_product(&self, k: i32) -> i32 {
    let k = k as usize;
    let len = self.prefix.len();
    if k >= len {
      return 0;
    }
    (self.prefix[len - 1] / self.prefix[len - 1 - k]) as i32
  }
}