Note that there are some explanatory texts on larger screens.

plurals
  1. POInterview Question... Trying to work it out, but couldn't get an efficient solution
    primarykey
    data
    text
    <p>I am stuck in one interview question.. The question is,</p> <blockquote> <p>*given two arrays A and B. A has integers unsorted. B has the same length as A and its values are in the set {-1,0,1}</p> <p>you have to return an array C with the following processing on A. </p> <p>if B[i] has 0 then C[i] must have A[i]<br> if B[i] has -1 then A[i] must be in C within the sub array C[0] - C[i-1] ie. left subarray<br> if B[i] has 1 then A[i] must be in C within the sub array C[i+1] - C[length(A)] ie right subarray. </p> <p>if no such solution exists then printf("no solution");*</p> </blockquote> <p>I applied following logics:-</p> <pre><code>int indMinus1 = n-1; int indPlus1 = 0; //while(indPlus1 &lt; n &amp;&amp; indMinus1 &gt; 0) while(indPlus1 &lt; indMinus1) { while(b[indMinus1] != -1) { if(b[indMinus1] == 0) c[indMinus1] = a[indMinus1]; indMinus1--; } while(b[indPlus1] != +1) { if(b[indPlus1] == 0) c[indPlus1] = a[indPlus1]; indPlus1++; } c[indMinus1] = a[indPlus1]; c[indPlus1] = a[indMinus1]; b[indMinus1] = 0; b[indPlus1] = 0; indMinus1--; indPlus1++; } </code></pre> <p>But this will not going to work,, for some cases like {1,2,3} >> {1,-1,-1}... One output is possible i.e. {2,3,1};</p> <p>Please help.... does their any algorithm technique available for this problem?</p> <p><strong>Correct Solution Code</strong></p> <pre><code>int arrange(int a[], int b[], int c[], int n) { for (int i = 0; i &lt; n; ++i) { if(b[i] == 0) c[i] = a[i]; } int ci = 0; for (int i = 0; i &lt; n; ++i) { if(b[i] == -1) { while(c[ci] != 0 &amp;&amp; ci &lt; i) ci ++; if(c[ci] != 0 || ci &gt;= i) return -1; c[ci] = a[i]; ci++; } } for (int i = 0; i &lt; n; ++i) { if(b[i] == 1) { while(c[ci] != 0 &amp;&amp; ci &lt; n) ci ++; if(c[ci] != 0 || ci &lt;= i) return -1; c[ci] = a[i]; ci++; } } return 0; } </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.
 

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