Product of Array Except Self


Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:
Input:  [1,2,3,4]
Output: [24,12,8,6] 
 
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division.

class Solution {
    public int[] productExceptSelf(int[] nums) {
       
        int prod = 1, k=0;
        int []res = new int[nums.length];
        for(int i=0;i<nums.length;i++){
            prod = 1;
            for(int j=0;j<nums.length;j++){
                if(i!=j){
                    prod *= nums[j];
                }
            }
            res[i] = prod;
        }
        return res;
    }
}

Try it on Leetcode

Here, avoid division method because array may contains zero.
Take each element in array and multiply with other elements in array using for loop.
After completion of each product store it in output array.
It consumes O(n^2) and space also.

If anyone had different solution , please leave it as a comment

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Smallest Range II