blind-75

Product of Array Except Self

Best Case: The best case is when all elements are non-zero.
Worst Case: The worst case occurs when there are zeros present.

Approach:

  1. Create two arrays for left and right products.
  2. Multiply corresponding values from both arrays.

Explanation to Interviewer:
“I would create two auxiliary arrays to hold left and right products for each index and then multiply them together to get the final result.”

Code Implementation:

JavaScript:

function productExceptSelf(nums) {
    const output = new Array(nums.length).fill(1);
    
    let leftProduct = 1;
    for (let i = 0; i < nums.length; i++) {
        output[i] *= leftProduct;
        leftProduct *= nums[i];
    }

    let rightProduct = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        output[i] *= rightProduct;
        rightProduct *= nums[i];
    }

    return output;
}

const nums = [1, 2, 3, 4];
console.log(productExceptSelf(nums)); // Output: [24, 12, 8, 6]

Python:

def product_except_self(nums):
    n = len(nums)
    output = [1] * n
    
    left_product = 1
    for i in range(n):
        output[i] *= left_product
        left_product *= nums[i]

    right_product = 1
    for i in range(n-1, -1, -1):
        output[i] *= right_product
        right_product *= nums[i]

    return output

nums = [1, 2, 3, 4]
print(product_except_self(nums)) # Output: [24, 12, 8, 6]