Logo

dev-resources.site

for different kinds of informations.

Product of Array Except Self

Published at
11/16/2023
Categories
Author
Harshed Abdulla
Categories
1 categories in total
open
Product of Array Except Self

The problem to solve is to return an array which contains product of the array elements expect itself

Eg: [1,2,3,4] = [24,12,8,6]

My first approach was to use two loops and if i!=j then it should take the product, but the time complexity was O(n^2)

Second approach was to use lproduct and rproduct. And then finally taking the product of each.

        int lproduct=1;
        for(int i=0;i<n;i++){
            lproducts[i]=lproduct;
            lproduct*=nums[i];
        }
        int rproduct=1;
        for(int i=n-1;i>=0;i--){
            rproducts[i]=rproduct;
            rproduct*=nums[i];
        }
        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = lproducts[i] * rproducts[i];
        }

Featured ones: