Product of Array Except Self

Gulshan KumarGulshan Kumar
2 min read

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;
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.