Sort Colors

Given an array of n colored objects, sort the array in place so that objects of the same color are adjacent, with the colors in a specific order.

Statement

Given an array of nn objects colored white, red, or blue, sort the array in place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

This problem is known as Dutch National Flag Problem. The idea is to attribute a color to each number and then arrange them following the order of colors on the Dutch flag.

We’ll use the integers 0, 1, and 2 to represent red, white, and blue, respectively.

Constraints

Input numbers are restricted to 0, 1, or 2.

Example

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.