Tutorialspoint
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.
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.
Constraints
  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysIBMPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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)

Steps to solve by this approach:

 Step 1: Initialize three pointers - low at 0, mid at 0, and high at the last index.

 Step 2: The low pointer maintains the boundary for placing 0s, high pointer for 2s.
 Step 3: Traverse the array using mid pointer and examine each element.
 Step 4: If current element is 0, swap it with element at low pointer and increment both low and mid.
 Step 5: If current element is 1, simply increment mid pointer as 1s are in correct position.
 Step 6: If current element is 2, swap it with element at high pointer and decrement high only.
 Step 7: Continue until mid pointer crosses high pointer, ensuring all elements are properly sorted.

Submitted Code :