Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm going to use array indices from 0 to N-1 because that's how we do things in the hood.</p> <p>You can rewrite the equation for b<sub>i</sub> like this: b<sub>i</sub> = (a<sub>0</sub>×a<sub>1</sub>×⋯×a<sub>i-1</sub>) × (a<sub>i+1</sub>×a<sub>i+2</sub>×⋯×a<sub>n-1</sub>), or more succinctly like this: b<sub>i</sub> = (∏<sub>j=0⋯i-1</sub> a<sub>j</sub>) × (∏<sub>j=i+1⋯n-1</sub> a<sub>j</sub>).</p> <p>(In case you're not familiar with it, ∏ is like ∑ but it multiplies the terms instead of adding them. Also, these formulas are not <em>quite</em> the same as the formula in your question, because according to the formula in your question, b<sub>i</sub> is undefined if a<sub>i</sub> is zero. However, I will assume that the intent is to cancel the a<sub>i</sub> in the numerator and denominator, even if it is zero.)</p> <p><strong>Anyway</strong>, you can compute the left subproducts (∏<sub>j=0⋯i-1</sub> a<sub>j</sub>) incrementally by traversing array a from 0 to n-1. You can compute the right subproducts (∏<sub>j=i+1⋯n-1</sub> a<sub>j</sub>) by traversing the array a from n-1 to 0.</p> <p>Thus the solution is to use two passes.</p> <p>The first pass is from 0 to N-1. Set each <code>b[i]</code> to the product of <code>a[j]</code> for <code>0 &lt;= j &lt; i</code>. This pass sets the b array to the left subproducts. This takes O(N) time and constant space for the loop counter.</p> <p>The second pass is from N-1 to 0. Update each <code>b[i]</code> by multiplying it by the product of <code>a[j]</code> for <code>i &lt; j &lt; N</code>. Thus pass updates the b array by multiplying each element by the appropriate right subproduct. This takes O(N) time and constant space for the loop counter and a temporary.</p> <p>Here's a Python solution:</p> <pre><code>b[0] = 1 for i in range(1, N): b[i] = b[i - 1] * a[i - 1] # Now every b[i] is the product of the a[j] where 0 &lt;= j &lt; i. t = 1 for i in range(N-1, -1, -1): b[i] = b[i] * t t *= a[i] # Now every b[i] is the product of the a[j] where 0 &lt;= j &lt; i # and the a[j] where i &lt; j &lt;= N-1. This is the desired output. </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload