## Google Interview Question

Senior Software Development Engineers**Team:**TEZ

**Country:**India

**Interview Type:**In-Person

```
#include <stdio.h>
enum { SIZE = 3 };
void printArr(int ai[]);
int main(void)
{
int arrA[] = {1,2,3,4};
int arrB[SIZE+1];
int m = 1;
printArr(arrA);
for(int i = 0; i <= SIZE; ++i)
{
for(int j = SIZE; j >= 0; --j)
{
if(i != j)
{
m = m * (arrA[j]);
}
}
arrB[i] = m;
m = 1;
}
printArr(arrB);
return 0;
}
void printArr(int ai[])
{
for(int i = 0; i <= SIZE; ++i)
printf("%d ", ai[i]);
printf("\n\n");
}
```

```
*/
public class ProductOfAllExceptSelf
{
public double[] getProducts(int[] input) throws Exception
{
if(input == null || input.length < 2)
throw new Exception("Invalid array - at least 2 elements needed");
else if(input.length == 2)
{
return new double[]{input[1], input[0]};
}
else
{
// check if zero exists
int N = input.length;
double[] result = new double[N];
int i, zeroCount = 0, zeroIndex = -1;
for(i = 0; i < N; i++)
{
if(input[i] == 0)
{
++zeroCount;
zeroIndex = i;
}
}
switch(zeroCount)
{
case 0:
// no zeros
double[] CP = new double[N];
CP[0] = input[0];
for(i = 1; i < N; i++)
{
CP[i] = CP[i - 1] * input[i];
}
for(i = 0; i < N; i++)
{
if(i == 0)
result[i] = CP[N - 1] / CP[0];
else if(i == N - 1)
result[i] = CP[N - 2];
else
result[i] = (CP[N - 1]*CP[i - 1])/CP[i];
}
break;
case 1:
// exactly one element is zero
int product = 1;
for(i = 0; i < N; i++)
{
if(i != zeroIndex)
{
product *= input[i];
}
else
{
result[i] = 0;
}
}
result[zeroIndex] = product;
break;
default:
// 2 or more zeros
for(i = 0; i < N; i++)
{
result[i] = 0;
}
break;
}
return result;
}
}
}
```

```
public static long[] productExceptItself (int[] arr) {
if (arr == null || arr.length <= 1) return new long[0];
int len = arr.length;
long[] answer = new long[len];
answer[0] = 1L;
for (int i = 1; i < len; i++) {
answer[i] = answer[i-1] * arr[i-1];
}
long rightProd = 1L;
for (int i = len-1; i >= 0; i--) {
answer[i] *= rightProd;
rightProd *= arr[i];
}
return answer;
}
```

Algorithm : Take the product of all item in the Array, loop from 0 to array.length make an array having item as- allProduct/array[i];

- Ritesh February 08, 2018