Sort Colors
You are given an array of integers where each integer represents a color: 0 for red, 1 for white, and 2 for blue. The goal is to sort this array in-place such that all the red elements come first, followed by all the white elements, and then all the blue elements. This is a common problem encountered in various algorithms and data processing tasks where you need to group elements based on distinct categories.
Problem Description
Your task is to sort an array containing only the integers 0, 1, and 2. The sorting must be done in-place, meaning you should modify the original array directly without creating a new one. The final arrangement of the array should have all the 0s grouped at the beginning, followed by all the 1s, and finally all the 2s at the end.
Key Requirements:
- Sort the array in-place.
- The final order must be
[0, 0, ..., 1, 1, ..., 2, 2, ...]. - You are only allowed to use a constant amount of extra space (O(1) space complexity).
Expected Behavior:
Given an input array, your function should return the modified array with the elements sorted according to the specified color order.
Edge Cases:
- An empty array.
- An array with only one color.
- An array with only two colors.
Examples
Example 1:
Input: [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Explanation: The input array is rearranged to group all 0s, then 1s, then 2s.
Example 2:
Input: [2, 0, 1]
Output: [0, 1, 2]
Explanation: A simple case where elements are already in a mixed order.
Example 3:
Input: [0]
Output: [0]
Explanation: An array with a single element remains unchanged.
Example 4:
Input: []
Output: []
Explanation: An empty array remains empty.
Constraints
- The length of the input array
numswill be between 0 and 300, inclusive. - Each element in
numswill be either 0, 1, or 2. - Your algorithm should run in linear time complexity (O(n)), where n is the number of elements in the array.
- You must solve the problem using O(1) extra space.
Notes
This problem is often referred to as the "Dutch National Flag problem." Consider using a partitioning approach. You can maintain pointers to keep track of the boundaries between the different colored sections as you iterate through the array. Try to avoid using any built-in sorting functions, as the goal is to implement the sorting logic yourself.