</>EmbeddedInterview

How do you find the product of an array except self without division?

MediumArrays & Strings (Coding Round)

Use a prefix product pass followed by a suffix product pass. The product except index i is the product of all elements before i times the product of all elements after i.

/* Assume all intermediate products fit int64_t.
   Output must not overlap input. */
void product_except(const int32_t a[],size_t n,int64_t out[])
{
    int64_t p=1;
    for(size_t i=0;i<n;++i) {
        out[i]=p;
        if(i+1<n) p*=a[i];
    }
    p=1;
    for(size_t i=n;i>0;) {
        --i;
        out[i]*=p;
        if(i) p*=a[i];
    }
}

[1,2,3,4] → [24,12,8,6]. Zero values need no special handling: one zero gives a nonzero result only at its position, two zeros give all zeros (assuming other products are representable). A single element returns the empty product 1.

Complexity: O(n) time, O(1) auxiliary space excluding output.