Sort Colors LeetCode Solution

Last updated on October 9th, 2024 at 10:43 pm

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

Topics

Array, Sort, Two-Pointers

Companies

Facebook, Microsoft, Pocketgems

Level of Question

Medium

Sort Colors LeetCode Solution

Sort Colors 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]

1. Sort Colors Leetcode Solution C++

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

2. 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++;        
    }
    }
}

3. 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)     
};

4. 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