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#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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;
}
static int[] productExceptSelf(int[] a) {
    int n = a.length;
    int[] 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;
}
vector<int> productExceptSelf(const vector<int>& a) {
    int n = (int)a.size();
    vector<int> res(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;
}
def product_except_self(a: list[int]) -> list[int]:
    n = len(a)
    res = [0] * n
    res[0] = 1
    for i in range(1, n):
        res[i] = res[i - 1] * a[i - 1]
    suffix = 1
    for i in range(n - 1, -1, -1):
        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.