## Yahoo Interview Question

Interns**Country:**Cananda

**Interview Type:**In-Person

Do remember that this solution will break if there are zeros in an array. These are special cases which interviewer looks for us to handle.

Here is sample code (similar solution) which handles zero possibility.

```
def mul(array):
array_mul = 1
has_zero = False
for i in array:
if i == 0:
has_zero = True
else:
array_mul *= i
for i in array:
if has_zero is True and i != 0:
print 0
elif has_zero is True and i == 0:
print array_mul
else:
print array_mul/i
```

```
// ZoomBA
nums = [ 2,3,1,0, 4,3,2 ]
def do_yahoo( nums ){
#(num_zeros, product) = lfold ( nums ,[0, 1] ) -> {
if ( $.o == 0 ){ $.p.0 += 1 } else { $.p.1 *= $.o }
$.p
}
product = num_zeros > 1 ? 0 : product
for ( nums ) {
println ( $ == 0 ? product : (product/$) )
}
}
do_yahoo ( nums )
```

Note the handling of zeros. Obviously, if there is one zero, the problem is non trivial. For multiple zeros, the problem is trivial again.

```
public int[] productExceptSelf(int[] nums) {
if(nums.length == 0){
return new int[0];
}
int[] result = new int[nums.length];
result[0]=1;
for(int i=1;i<nums.length;i++){
result[i]=result[i-1]*nums[i-1];
}
int product = 1;
for(int i=nums.length-1;i>=0;i--){
result[i]=result[i]*product;
product = product*nums[i];
}
return result;
}
```

```
import java.util.Arrays;
public class ProductWholeArrayExceptElement {
public static void main(String[] args){
int[] arr = {2,3,4,1,5,2};
System.out.println(Arrays.toString(printProductExceptElement(arr)));
}
static int prod = 1;
private static int[] printProductExceptElement(int[] arr){
int[] result = new int [arr.length];
for(int i=0;i<arr.length;i++){
prod *= arr[i];
}
for(int i=0;i<arr.length;i++){
result[i] = prod/arr[i];
}
return result;
}
}
```

Complexity - O(n)

The same as all previus posts

```
public static int[] GetProducts(int[] a)
{
if (a == null || a.Length == 0)
return new int[0];
long product = 1;
foreach (var numb in a)
product *= numb;
int[] result = new int[a.Length];
for (int i=0; i < a.Length; i++)
result[i] = (int)(product / a[i]);
return result;
}
```

This problem we solve o(n) time complexity and o(1) space complexity but if anyone has better solution so please share thier solution.

```
printNum()
{
int arr[]={2,3,1,4,3,2};
int size=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<size;i++)
{
mul = mul*arr[i];
}
for(i=0;i<size;i++)
{
printf("%d\n",mul/arr[i]);
}
}
```

- Anonymous October 09, 2016