Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Can be done in <strong><em>O(n^2)</em></strong> with <em>2 pointers method</em>.<br/> <br/> Sort the arrays. Now do following:<br/> Set <strong><em>ans = 0</em></strong>.<br/> Have an external loop running through array <strong><em>a</em></strong> with index <strong><em>i</em></strong>. Now set <strong><em>j = 0, k = n - 1</em></strong>.<br/> Look at <strong><em>sum = a[ i ] + b[ j ] + c[ k ]</em></strong>.<br/> If <strong><em>sum &lt; 0</em></strong>, increase <strong><em>j</em></strong>.<br/> If <strong><em>sum > 0</em></strong> decrease <strong><em>k</em></strong>.<br/> If <strong><em>sum == 0</em></strong>, find the range of elements equal to <strong><em>b[ j ]</em></strong> and <strong><em>c[ k ]</em></strong> and add ranges lengths product to the answer. Then set <strong><em>j</em></strong> and <strong><em>k</em></strong> to first elements out of that ranges.<br/> This works because arrays are sorted and addition is a linear function.<br/> Internal part runs in <strong>O(n)</strong>, with overall <strong>O(n^2)</strong> complexity.</p> <p>Example code in C++:</p> <pre class="lang-cpp prettyprint-override"><code>sort( a, a + n ); sort( b, b + n ); sort( c, c + n ); ans = 0; for( i = 0; i &lt; n; ++i ) { j = 0, k = n - 1; while( j &lt; n &amp;&amp; k &gt; 0 ) { sum = a[ i ] + b[ j ] + c[ k ]; if( sum &lt; 0 ) ++j; else if( sum &gt; 0 ) --k; else { // find the equal range for( jj = j; jj &lt; n &amp;&amp; b[ jj ] == b[ j ]; ++jj ); for( kk = k; kk &gt;= 0 &amp;&amp; c[ kk ] == c[ k ]; --kk ); // add pairs quantity from these ranges ans += ( jj - j ) * ( k - kk ); j = jj, k = kk; } } </code></pre> <p><em><strong>Note</em></strong>: Sorting of array <strong><em>a</em></strong> is not necessary, just did it to look good :)</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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