Finding products of all other members of an array 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 &lt; arr.length; i++) {
        int product = 1;

        for (int j = 0; j &lt; arr.length; j++) {
            if (i != j) {
                product *= arr[j];
            }
        }

        products[i] = product;
    }

    return products;
}
This could be done with two consecutive loops (instead of nested loops), making it O(N) instead of O(N^2).

In the first loop you calculate the total product of all non-zero elements (and the number of zeros).

If there are more than one zero, return result as is, since all elements already default to zero.

In the second you either set the result element to zero or to total product divided by the current element depending on the number of zeros in the data and the value of the current element.

BTW, There are a lot of blog posts and even some research written about the pointlessness of this kind of interview questions.