Product of array except self

For every index, multiply the product of everything to its left by the product of everything to its right. No division needed.

Time O(n)Space O(1) extraCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Fill res[i] with the product of everything to its left in one left-to-right pass. Then sweep right-to-left, multiplying in a running "suffix" product of everything to the right. Combining the two avoids ever dividing by a[i], so it still works if a value were zero.

Code

public static int[] ProductExceptSelf(int[] a) {
    int n = a.Length;
    var res = new int[n];
    res[0] = 1;
    for (int i = 1; i < n; i++)
        res[i] = res[i - 1] * a[i - 1];
    int suffix = 1;
    for (int i = n - 1; i >= 0; i--) {
        res[i] *= suffix;
        suffix *= a[i];
    }
    return res;
}

Tips

In the .NET library

Both passes read and write the same res array, so the only extra variable is suffix itself - the output array does not count toward the space bound.