Tutorialspoint
Problem
Solution
Submissions

Sort Colors

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to sort an array of integers containing only 0s, 1s, and 2s. This is also known as the Dutch National Flag problem. The solution should sort the array in-place with a single traversal of the array.

Example 1
  • Input: nums[] = {2, 0, 2, 1, 1, 0}
  • Output: {0, 0, 1, 1, 2, 2}
  • Explanation:
    • Step 1: The array is [2, 0, 2, 1, 1, 0]
    • Step 2: After sorting, all 0s come first, followed by all 1s, and then all 2s.
    • Step 3: Therefore, the sorted array is [0, 0, 1, 1, 2, 2]
Example 2
  • Input: nums[] = {1, 2, 0, 1, 2, 0}
  • Output: {0, 0, 1, 1, 2, 2}
  • Explanation:
    • Step 1: The array is [1, 2, 0, 1, 2, 0]
    • Step 2: Using the Dutch National Flag algorithm, we sort the array in a single pass.
    • Step 3: After sorting, all 0s come first, followed by all 1s, and then all 2s.
    • Step 4: Therefore, the sorted array is [0, 0, 1, 1, 2, 2]
Constraints
  • 1 <= nums.length <= 300
  • nums[i] is either 0, 1, or 2
  • You must solve this problem without using the library's sort function
  • Time Complexity: O(n) - one-pass algorithm
  • Space Complexity: O(1) - constant extra space
ArraysEYD. E. Shaw
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 the Dutch National Flag algorithm with three pointers: low, mid, and high.
  • The low pointer keeps track of the boundary for 0s.
  • The mid pointer traverses the array and represents the boundary for 1s.
  • The high pointer keeps track of the boundary for 2s.
  • Traverse the array with the mid pointer until it crosses the high pointer.

Steps to solve by this approach:

 Step 1: Initialize three pointers: low = 0, mid = 0, and high = n-1.

 Step 2: The region before low contains 0s, between low and mid contains 1s, and after high contains 2s.
 Step 3: The region between mid and high contains elements that are yet to be sorted.
 Step 4: Traverse the array with the mid pointer until it crosses the high pointer.
 Step 5: If nums[mid] is 0, swap nums[low] and nums[mid], then increment both low and mid.
 Step 6: If nums[mid] is 1, just increment mid.
 Step 7: If nums[mid] is 2, swap nums[mid] and nums[high], then decrement high.

Submitted Code :