Bloomberg LP Interview Question
Software Engineer / DevelopersEven without counting sort this can be done in O(n) time
Ri = Size-1
Bi = 0
while (Bi > Ri && Bi < Size-1 && Ri >0 )
{
while (Array[Bi] == Red) Bi++;
while (Array[Ri]) == Blue) Ri--;
else if (Bi > Ri)
{swap (Array[Bi],Array[Ri]);}
}
this is essentially partition routine of quicksort.
though it has two level of looping essentially it is O(n) as the iteration of indeices is once
Amit's logic can be generalized, for R,G,B... and so on. by using Array of place pointer.
In the above example and Bi and Ri are used as place pointers, same way. We are using two pointer because we know we have two type of objects.
Later on if number of R,G,B... are numerious, then searchin in array will require hashing.
for (int i=0; i<n; i++)
{
hash[arr[i]] ++;
}
void sort(char* a, int l)
- Anonymous July 15, 2010{
int t = 0;
for (p = 0; p < l; p++)
{
if (a[p] == 'R' && p != t)
{
a[p] = a[t];
a[t++] = 'R';
}
}
}