Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder Array of Red, Blue and Green balls

In one of my interviews the interviewer asked me - An array of some size contains Red, Blue and Green balls all mixed up randomly. like RGBBBRRGGG, where RGB is for Red, Green and Blue.

What is the most optimal way to end up with an array like- RRRRGGGGBBBB i.e. all R's, all G's and all B's together.

I proposed converting all Red, Blue, Green to their ASCII values and then running the most efficient sorting algorithm on it. But he wasn't impressed . Any other more efficient solution to this problem ? with lowest space and time complexity ?

like image 264
geeky_bat Avatar asked Aug 11 '12 06:08

geeky_bat


2 Answers

Simply go through the array and count the occurrence of R, G and B respectively. Then, output the string. Linear time.

like image 108
timrau Avatar answered Nov 11 '22 20:11

timrau


The interviewer might have wanted to know if you were familiar with the Dutch national flag problem. It has a simple linear solution. There are C++ and Java examples on the Wikipedia page.

like image 42
Blastfurnace Avatar answered Nov 11 '22 19:11

Blastfurnace