viralsanghavi7
BAN USER/**
This solution runs in O(n).
It traverse through entire array to calculate product. If it finds zero at any element, it will remember that index and breaks the loop.
Now there can be 2 cases:
1) Zero element found at any index: In this case it will set all other index as zero in resulting array and calculate product for zero index element.
2) No element is zero in array: Divide product with individual value of an array to calculate new array elements.
**/
public int[] product(int[] arr){
int[] returnArray = new int[arr.length];
int zeroElementIndex = -1;
int product = 1;
for(int i=0;i<arr.length;i++){
if(arr[i] == 0){
zeroElementIndex = i;
break;
}else{
product = product * arr[i];
}
}
if(zeroElementIndex != -1){
product =1;
for(int j=0;j<arr.length;j++){
if(j != zeroElementIndex)
{
returnArray[j] = 0;
product = product * arr[j];
}
}
returnArray[zeroElementIndex] = product;
}else{
for(int j=0;j<arr.length;j++){
returnArray[j] = product/arr[j];
}
}
return returnArray;
}
- viralsanghavi7 February 28, 2015