Last updated on March 7th, 2025 at 07:22 pm
Here, we see a Sort Colors LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Array, Sort, Two-Pointers
Companies
Facebook, Microsoft, Pocketgems
Level of Question
Medium

Sort Colors LeetCode Solution
Table of Contents
1. 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]
2. Coding Pattern Used in Solution
The coding pattern used in the Java code is Two Pointers. The two pointers (p1
and p2
) are used to segregate the 0
s and 2
s while iterating through the array. The JavaScript and Python codes use a Counting/Counting Sort pattern, where the frequency of each number is counted, and the array is reconstructed based on the counts. The C++ code uses the Sorting pattern by directly calling the sort
function.
3. Code Implementation in Different Languages
3.1 Sort Colors C++
class Solution { public: void sortColors(vector<int>& nums) { sort(nums.begin(), nums.end()); } };
3.2 Sort Colors 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.3 Sort Colors 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) };
3.4 Sort Colors 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
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n log n) | O(1) |
Java | O(n) | O(1) |
JavaScript | O(n) | O(n) |
Python | O(n) | O(1) |
- The Java solution is the most efficient in terms of both time and space complexity.
- The C++ solution is less efficient due to the use of a general-purpose sorting algorithm.
- The JavaScript and Python solutions are efficient in time but differ in space complexity due to the way the array is reconstructed.