DEV Community

Harshed Abdulla
Harshed Abdulla

Posted on

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];
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)