Using BucketSort to sort an array of colors
A common question, especially as warm-up question in technical interviews, is the following: given a sorted list of colored balls where some balls are black and some are white, rearrange the set in such a way to have the black balls ahead of the white ones. Once the candidate is done with it, a follow-up question comes with an introduction of a third color, say green. The image below exemplifies the before-after states for this question: I've seen solutions using the following approaches: 1) Brute-force N^2-time (similar to BubbleSort) 2) Two-pointers (head and tail) solutions (which gets complicated with more colors) 3) Even a QuickSort-like solution (attempting to get it down to NLogN-time) There is an easier solution that works well for this case, but there is one key characteristic for this problem: the order of the balls within a group with the same color is irrelevant . This is crucial in order to be able to use a bucket (or count) sort approach. The approach wil...