I had the following interview question: Given an array of integers, for each member of the array find the product of all the other members of the array. So for instance, if you have this array:
{3, 1, 2, 0, 4}
you should end up with this:
{0 0 0 24 0}
I wrote this code which uses two loops, but I couldn't come up with a solution with just one loop. Can anyone help me?
public int[] findProducts(int[] arr) {
int[] products = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int product = 1;
for (int j = 0; j < arr.length; j++) {
if (i != j) {
product *= arr[j];
}
}
products[i] = product;
}
return products;
}