Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

# Sort Colors LeetCode Solution

## Problem – Sort Colors

Given an array `nums` 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.

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

You must solve this problem without using the library’s sort function.

Example 1:

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

Example 2:

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

Constraints:

• `n == nums.length`
• `1 <= n <= 300`
• `nums[i]` is either `0``1`, or `2`.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

### Sort Colors LeetCode Solution in Python

``````def sortColors(self, nums):
red, white, blue = 0, 0, len(nums)-1

while white <= blue:
if nums[white] == 0:
nums[red], nums[white] = nums[white], nums[red]
white += 1
red += 1
elif nums[white] == 1:
white += 1
else:
nums[white], nums[blue] = nums[blue], nums[white]
blue -= 1
``````

### Sort Colors LeetCode Solution in C++

``````class Solution {
public:
void sortColors(vector<int>& nums)
{
int tmp = 0, low = 0, mid = 0, high = nums.size() - 1;

while(mid <= high)
{
if(nums[mid] == 0)
{
tmp = nums[low];
nums[low] = nums[mid];
nums[mid] = tmp;
low++;
mid++;
}
else if(nums[mid] == 1)
{
mid++;
}
else if(nums[mid] == 2)
{
tmp = nums[high];
nums[high] = nums[mid];
nums[mid] = tmp;
high--;
}
}
}
};
``````

### Sort Colors LeetCode Solution in Java

``````public void sortColors(int[] nums) {
// 1-pass
int p1 = 0, p2 = nums.length - 1, index = 0;
while (index <= p2) {
if (nums[index] == 0) {
nums[index] = nums[p1];
nums[p1] = 0;
p1++;
}
if (nums[index] == 2) {
nums[index] = nums[p2];
nums[p2] = 2;
p2--;
index--;
}
index++;
}
}
``````
##### Sort Colors LeetCode Solution Review:

In our experience, we suggest you solve this Sort Colors LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Sort Colors LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Sort Colors LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions