## # 75. Sort Colors

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

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

``````Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
``````

• A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
• Could you come up with a one-pass algorithm using only constant space?

### # Solution

Approach 1: Two passes - counting sort.

Approach 2: One pass - three pointers.

### # Code (Python)

Approach 1:

``````from collections import Counter

def sortColors(self, nums):
counts = Counter(nums)
i = 0
for num in (0, 1, 2):
for j in range(counts[num]):
nums[i] = num
i += 1
``````

Approach 2:

``````    def sortColors(self, nums):
pointer_0, pointer_2, current = 0, len(nums) - 1, 0
while current <= pointer_2:
if nums[current] == 0:
nums[current], nums[pointer_0] = nums[pointer_0], 0
pointer_0 += 1

# Either of the following line works. Want to make sure current >= pointer_0 always,
# and if current > pointer_0, the array looks like [0, 0, 0, 1, 1, 0, ...], so after the swap current always points to a 1
#                                                 (pointer_0)|     |(current)

#current += 1 # OR:
current = max(current, pointer_0)
elif nums[current] == 2:
nums[current], nums[pointer_2] = nums[pointer_2], 2
pointer_2 -= 1
else:
current += 1
``````

### # Code (C++)

Approach 1:

``````// Two passes - counting sort.
class Solution {
public:
void sortColors(vector<int>& nums) {
int colorCount = {0};
for (int i = 0; i < nums.size(); ++i)
{
colorCount[nums[i]]++;
}
int i = 0;
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < colorCount[j]; ++k)
{
nums[i++] = j;
}
}
}
};
``````

Approach 2:

``````// One pass - three pointers.
class Solution {
public:
void sortColors(vector<int>& nums) {
int p0 = 0;
int p1 = 0;
int p2 = nums.size() - 1;
while (p0 < nums.size() && p1 < nums.size() && p2 >= 0)
{
if (nums[p0] == 0)
p0++;
else if (nums[p2] == 2)
p2--;
else if (p1 > p0 && nums[p1] == 0)
std::swap(nums[p1], nums[p0]);
else if (p1 < p2 && nums[p1] == 2)
std::swap(nums[p1], nums[p2]);
else
p1++;
}
}
};
``````