Leetcode - 238. Product of Array Except Self

Rakesh Reddy Peddamallu - Sep 10 - - Dev Community

So we should not be using the division operator as the question says
but adding the code anyways
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
. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player