Product of Array Except Self

Product of Array Except Self

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.

LeetCode Problem - 238

class Solution {
    // Method to compute the product of all elements in the array except self
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length; // Get the length of the array
        int[] forwardArray = new int[len]; // Array to store products of elements before the current element
        int[] backwardArray = new int[len]; // Array to store products of elements after the current element
        int[] result_array = new int[len]; // Array to store the final result

        forwardArray[0] = 1; // Initialize the first element of forwardArray to 1
        backwardArray[len-1] = 1; // Initialize the last element of backwardArray to 1

        // Calculate the products of elements before the current element
        for(int i = 1; i < len; i++){
            forwardArray[i] = nums[i-1] * forwardArray[i-1];
        }

        // Calculate the products of elements after the current element
        for (int j = len - 2; j >= 0; j--){
            backwardArray[j] = nums[j+1] * backwardArray[j+1];
        }

        // Compute the final result by multiplying corresponding elements from forwardArray and backwardArray
        for (int k = 0; k < len; k++){
            result_array[k] = forwardArray[k] * backwardArray[k];
        }

        // Return the final result
        return result_array;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!