
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Sort Colors
								Certification: Intermediate Level
								Accuracy: 100%
								Submissions: 1
								Points: 10
							
							Write a JavaScript program to sort an array containing only 0s, 1s, and 2s in-place. The colors red, white, and blue are represented by integers 0, 1, and 2 respectively. You must solve this problem without using the library's sort function and in a single pass.
Example 1
- Input: nums = [2,0,2,1,1,0]
- Output: [0,0,1,1,2,2]
- Explanation: - The array contains red (0), white (1), and blue (2) colors. 
- We need to sort them so all reds come first, then whites, then blues. 
- After sorting: [0,0,1,1,2,2] where 0s are grouped first, then 1s, then 2s. 
- The array is now properly sorted with colors in order.
 
- The array contains red (0), white (1), and blue (2) colors. 
Example 2
- Input: nums = [2,0,1]
- Output: [0,1,2]
- Explanation: - The array contains one of each color: red (0), white (1), blue (2). 
- After sorting, red comes first, then white, then blue. 
- The final sorted array is [0,1,2]. 
- Each color is in its correct position.
 
- The array contains one of each color: red (0), white (1), blue (2). 
Constraints
- n == nums.length
- 1 <= n <= 300
- nums[i] is either 0, 1, or 2
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use three pointers: low, mid, and high to partition the array
- low pointer tracks the boundary for 0s, high pointer tracks the boundary for 2s
- mid pointer is used to traverse the array and examine each element
- When nums[mid] is 0, swap with nums[low] and increment both low and mid
- When nums[mid] is 1, just increment mid pointer
- When nums[mid] is 2, swap with nums[high] and decrement high (don't increment mid)
