This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.
Question:
Yo
Okey, here is my approach.
e.g a[] = { 1,0,0,0,1,1,1,0,0,1};
Pseudocode:
count1 = 0
and count2 = (n/2)+1
Traverse through the array,
if(arr[ i ] == 1)
{
arr[ i ] = count1++;
} else {
arr[ i ] = count2++
};
At the end of the traversal, you have array filled with numbers 0 to n-1 like:
a[ ] = { 0, 5, 6, 7, 1, 2, 3, 8, 9 4}
Now the problem comes to sort the above resultant array, this can be done in O(N) as below:
for(j = 0; j <= 1; j++)
{
for(i = 0; i
Note: j loop runs only twice irrespective on 'n' and has constant complexity. The order of this whole loop is 2*n = O(n).
After the array is sorted, Again traverse through the array and set elements arr[0]
to arr[n/2]
to '1'
and arr[(n/2)+1]
to arr[n]
as '0'
.
Space complexity is constant and time complexity is O(step2) + O(step4) + O(step5) = n + 2n +n = 4*n = O(n).