Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue (0, 1, 2).
Examples
nums = [2,0,2,1,1,0]
[0,0,1,1,2,2]
Sort in-place: 0s first, then 1s, then 2s.
Constraints
- •
n == nums.length - •
1 <= n <= 300 - •
nums[i] is either 0, 1, or 2.
Approaches
Count occurrences of each color and overwrite the array.
def sort_colors(nums):
count = [0, 0, 0]
for num in nums:
count[num] += 1
idx = 0
for color in range(3):
for _ in range(count[color]):
nums[idx] = color
idx += 1First pass: move all 0s to the front. Second pass: move all 1s after the 0s.
def sort_colors(nums):
idx = 0
for i in range(len(nums)):
if nums[i] == 0:
nums[idx], nums[i] = nums[i], nums[idx]
idx += 1
for i in range(idx, len(nums)):
if nums[i] == 1:
nums[idx], nums[i] = nums[i], nums[idx]
idx += 1Use three pointers: low for 0s, mid for current, high for 2s. Single pass.
Diagram
def sort_colors(nums):
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1Complexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Counting Sort | O(n) | O(1) | Count occurrences of each color and overwrite the array. |
| Two Pass - Swap | O(n) | O(1) | First pass: move all 0s to the front. Second pass: move all 1s after the 0s. |
| Dutch National Flag (Three Pointers) | O(n) | O(1) | Use three pointers: low for 0s, mid for current, high for 2s. Single pass. |
Count occurrences of each color and overwrite the array.
First pass: move all 0s to the front. Second pass: move all 1s after the 0s.
Use three pointers: low for 0s, mid for current, high for 2s. Single pass.
Common Mistakes
Using two separate passes when a single-pass solution exists
Not incrementing mid after swapping with low
Decrementing high before checking the swapped element