I am going to use array indices from 0 to N-1 because this is how we do things in the hood.
You can rewrite the equation for b i as follows: b i = (a 0 × a 1 × ⋯ × a i-1 ) × (a i + 1 × a i + 2 × ⋯ × a n-1 ) or more succinctly: b i = (Π j = 0 ⋯ i-1 a j ) × (Π j = i + 1 ⋯ n-1 a j ).
(In case you are not familiar with it, Π is similar to Σ, but it multiplies the terms instead of adding them. Moreover, these formulas are not quite the same as the formula in your question, since according to the formula your question is, b i is undefined if a i is equal to zero. However, I will assume that the goal is to cancel a i in the numerator and denominator, even if it is zero.)
In any case, you can calculate the left offal (Π j = 0 ⋯ i-1 a j ) step by step by moving the array a from 0 to n-1. You can calculate the correct offal (Π j = i + 1 ⋯ n-1 a j ) by going through array a from n-1 to 0.
So the solution is to use two passes.
First pass from 0 to N-1. For each b[i] specify the product a[j] for 0 <= j < i . This pass sets array b to left offal. It takes O (N) time and constant space for the loop counter.
Second pass from N-1 to 0. Update each b[i] by multiplying it by the product a[j] for i < j < N . Thus, the array b is updated by multiplying each element by the corresponding legal subproduct. It takes O (N) time and constant space for the cycle counter and time.
Here's a Python solution:
b[0] = 1 for i in range(1, N): b[i] = b[i - 1] * a[i - 1]
rob mayoff
source share