DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on

Leetcode - 238. Product of Array Except Self

So we should not be using the division operator as the question says
but adding the code anyways

idea is there are three cases; -> normal division
1 -> when no zeroes in array
2 -> when 1 zero in array -> return 0 for all except at 1 place
3 -> when more than 1 zeros in array -> return 0 for all
Using division operator

function productExceptSelf(nums) {
    // Step 1: Compute the total product of all elements
    let totalProduct = 1;
    let zeroCount = 0;

    for (let num of nums) {
        if (num === 0) {
            zeroCount++;
            if (zeroCount > 1) {
                return Array(nums.length).fill(0);
            }
        } else {
            totalProduct *= num;
        }
    }

    // Step 2: Compute the result array using division
    const result = [];
    for (let num of nums) {
        if (zeroCount === 0) {
            result.push(totalProduct / num);
        } else if (zeroCount === 1 && num === 0) {
            result.push(totalProduct);
        } else {
            result.push(0);
        }
    }

    return result;
}
Enter fullscreen mode Exit fullscreen mode
  1. Compute Total Product and Count Zeros:

  2. Traverse the array to compute the total product of non-zero elements and count the number of zeros.
    If there is more than one zero, the result will be all zeros.
    If there is exactly one zero, only the position where the zero is will have the product of all non-zero elements; all other positions will be zero.

  3. Compute Result Using Division:
    For each element, if there are no zeros, divide the total product by the element.
    If there is exactly one zero and the element is zero, the result for that position is the total product; otherwise, it is zero.

Using Prefix Array

This is the solution i found in neetcode

Javascript Code

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function(nums) {
    let res = new Array(nums.length).fill(1); 
    let prefix = 1

    for(let i=0;i<nums.length;i++){
            res[i] = prefix;
            prefix *= nums[i];
    }
    let postfix = 1
    for(let i=nums.length-1;i>=0;i--){
        res[i] *= postfix;
        postfix *= nums[i];
   }
   return res

};
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)