# Sort Colors LeetCode Solution

Here, We see Sort Colors LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

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]
```

## Sort Colors Leetcode Solution C++

``````class Solution {
public:
void sortColors(vector<int>& nums) {
sort(nums.begin(), nums.end());
}
};```Code language: CSS (css)```

## Sort Colors Leetcode Solution Java

``````class Solution {
public void sortColors(int[] nums) {
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++;
}
}
}```Code language: HTML, XML (xml)```

## Sort Colors Leetcode Solution JavaScript

``````var sortColors = function(nums) {
let one=0, zero=0, two=0
for(let elem of nums){
if(elem == 0) zero++
else if ( elem == 1) one ++
else two ++
}
nums.length=0
for(let i=0;i<zero;i++) nums.push(0)
for(let i=0;i<one;i++) nums.push(1)
for(let i=0;i<two;i++) nums.push(2)
};```Code language: JavaScript (javascript)```

## Sort Colors Leetcode Solution Python

``````class Solution(object):
def sortColors(self, nums):
c0 = c1 = c2 = 0
for num in nums:
if num == 0:
c0 += 1
elif num == 1:
c1 += 1
else:
c2 += 1
nums[:c0] = [0] * c0
nums[c0:c0+c1] = [1] * c1
nums[c0+c1:] = [2] * c2``````
Scroll to Top