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