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: Link | Click Here

class Solution {
    public int[] productExceptSelf(int[] nums) {
        // Get the length of the input array
        int len = nums.length;

        // Arrays to store the product of elements to the left and right of each element
        int[] forwardArray = new int[len];
        int[] backwardArray = new int[len];

        // Result array to store the final product for each element
        int[] resultArray = new int[len];

        // Initialize the first element in the forward and backward arrays
        forwardArray[0] = 1;
        backwardArray[len - 1] = 1;

        // Calculate the product of elements to the left of each element using the forwardArray
        for (int i = 1; i < len; i++) {
            forwardArray[i] = nums[i - 1] * forwardArray[i - 1];
        }

        // Calculate the product of elements to the right of each element using the backwardArray
        for (int j = len - 2; j >= 0; j--) {
            backwardArray[j] = nums[j + 1] * backwardArray[j + 1];
        }

        // Calculate the final product for each element by multiplying corresponding values from both arrays
        for (int k = 0; k < len; k++) {
            resultArray[k] = forwardArray[k] * backwardArray[k];
        }

        // Return the final result array
        return resultArray;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!