Skip to main content
Back to problems
#238
Medium Algorithms

Product of array except self

Array Prefix Sum
68.6% acceptance
Jan 12, 2026
25717
1687
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
    let n = nums.len();
    let mut result = vec![1; n];
    
    let mut prefix = 1;
    for i in 0..n {
      result[i] = prefix;
      prefix *= nums[i];
    }
    
    let mut suffix = 1;
    for i in (0..n).rev() {
      result[i] *= suffix;
      suffix *= nums[i];
    }
    
    result
  }
}