Learn-dsa..in 30 days!



























CC-10 : For each element of array, find product of all elements except self.

Description:

Given an input integer array arr. For all elements of the array, find the product of all elements except current element.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4,5} 120,60,40,30,24
arr={0,1,2,3,4} 24,0,0,0,0
arr={0,2,3,4,0} 0,0,0,0,0
arr={1,0,3,0,5} 0,0,0,0,0

Pseudocode:

The java method should accept following input parameters: arr (int array).
Initialize array called arrayOfProducts with length-arr.length, which will be used to store the products of all elements except current element.
While finding products of array elements, if any element is 0, then product of all elements become 0. So, to handle this special case of 0, we should first iterate through arr and find number of 0s in the array.
Iterate through the array using a for loop and find the count of zeros. If number of zeros is 0 find product of all element prodOfElements in the same for loop.
If count of zeroes is more than 1, then populate 0 in all indices of arrayOfProducts.
If count of zeroes is 1, then for the arr index that has zero, populate product of all other index values of arr except idx in arrayOfProducts[idx]. For all other indices, populate 0.
If count of zeroes is 0, then iterate through the arr with a for loop:
For each arr[idx], populate arrayOfProducts[idx] with (prodOfElements/ arr[idx]).
After above for loop ends return arrayOfProducts.

Code:

public int[] arrayProductOfAllElementsExceptSelf(int[] arr) throws Exception{
	int countOfZeros=0;	int indexOfZero=0;
	int prodOfElements=1;
	int arrayofProducts[]=new int[arr.length];
	for(int idx=0; idx < arr.length; idx++) {
		if (arr[idx]==0) {
			countOfZeros++;
			indexOfZero=idx;
		}
		else {
			prodOfElements*=arr[idx];
		}
	}
	for(int idx=0; idx < arr.length; idx++) {
		if (countOfZeros==0) {
			arrayofProducts[idx]=prodOfElements/arr[idx];			
		}if (countOfZeros==1) {
			if (idx==indexOfZero) {
				arrayofProducts[idx]=prodOfElements;
			}else {
				arrayofProducts[idx]=0;
			}
		}if (countOfZeros>1) {
			arrayofProducts[idx]=0;
		}
	}
	return arrayofProducts;					
}

Click here to download and run code and test cases !