Problem
An array contains only the values 0, 1 and 2. Sort it in place so the zeros come first, then the ones, then the twos.
Original: LeetCode 75: Sort Colors.
Examples
Example 1
`nums = [2, 0, 2, 1, 1, 0]``nums = [0, 0, 1, 1, 2, 2]`Example 2
`nums = [2, 0, 1]``nums = [0, 1, 2]`Constraints
n == nums.length1 <= n <= 300nums[i]is either 0, 1, or 2.
Hints
Hint 1
You must rearrange the input array itself. A counting pass is allowed, but a one-pass partition is the usual follow-up.
Hint 2
Three fixed values and an in-place requirement is the Dutch-national-flag partition: read/write pointers from both ends.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Count the zeros, ones and twos, then overwrite the array in that order. Two passes, linear time, constant space.
Optimal. Keep low as the next place for a 0, high as the next place for a 2, and i as the scan. Swap a 0 with low and advance both, swap a 2 with high and only shrink high, and skip a 1.
Alternative. A library sort is correct but O(n log n), and it hides the partition.
Complexity
- Time
- O(n)
O(n) time, O(1) extra space.
- Space
- O(1)
Code
def sort_colors(nums: list[int]) -> None:
low, i, high = 0, 0, len(nums) - 1
while i <= high:
if nums[i] == 0:
nums[low], nums[i] = nums[i], nums[low]
low += 1
i += 1
elif nums[i] == 2:
nums[high], nums[i] = nums[i], nums[high]
high -= 1
else:
i += 1
if __name__ == "__main__":
a = [2, 0, 2, 1, 1, 0]
sort_colors(a)
assert a == [0, 0, 1, 1, 2, 2]
b = [2, 0, 1]
sort_colors(b)
assert b == [0, 1, 2]
print("ok")import java.util.Arrays;
public class SortColors {
static void sortColors(int[] nums) {
int low = 0, i = 0, high = nums.length - 1;
while (i <= high) {
if (nums[i] == 0) {
int t = nums[low]; nums[low] = nums[i]; nums[i] = t;
low++;
i++;
} else if (nums[i] == 2) {
int t = nums[high]; nums[high] = nums[i]; nums[i] = t;
high--;
} else {
i++;
}
}
}
public static void main(String[] args) {
int[] a = {2, 0, 2, 1, 1, 0};
sortColors(a);
if (!Arrays.equals(a, new int[] {0, 0, 1, 1, 2, 2})) throw new AssertionError(Arrays.toString(a));
int[] b = {2, 0, 1};
sortColors(b);
if (!Arrays.equals(b, new int[] {0, 1, 2})) throw new AssertionError(Arrays.toString(b));
System.out.println("ok");
}
}Edge cases
- Official samples: [2,0,2,1,1,0] becomes [0,0,1,1,2,2], and [2,0,1] becomes [0,1,2].
- Already sorted input, or an array of a single value, must stay unchanged.
- When you swap a 2 in, do not advance
i, because the value that arrived has not been classified yet.
Follow-ups
- The two-pass counting sort is easier to write if the interviewer does not require one pass.
- The same partition extends to more buckets only with extra counting or a full sort.
Interview script
"The array has only three values, so I can partition it like the Dutch national flag: a left pointer writes zeros, a right pointer writes twos, and the scan leaves ones in the middle. One pass, constant space. I do not advance the scan after swapping in a 2, because that new value still needs a check."
Source: LeetCode 75: Sort Colors
k-Sum
Sources (1)
- LeetCode 75: Sort Colorsleetcode.com