Full answer
Problem
Given nums with values only 0, 1 or 2, sort it in place in one pass without using a library sort.
Example: [2, 0, 2, 1, 1, 0] becomes [0, 0, 1, 1, 2, 2].
Constraints: 1 <= len(nums) <= 300 (the approach scales to any size), O(1) extra space.
Brute force
Counting sort: count the 0s, 1s and 2s in one pass, then overwrite the list in a second pass. O(n) time and O(1) space, but two passes. A library sort is O(n log n).
Optimal approach
Pointers: low = 0, mid = 0, high = n - 1. While mid <= high:
nums[mid] == 0: swap withnums[low], thenlow += 1,mid += 1.nums[mid] == 1:mid += 1.nums[mid] == 2: swap withnums[high], thenhigh -= 1only.
Why it works
The invariant is nums[:low] are 0, nums[low:mid] are 1, nums[mid:high + 1] are unknown, nums[high + 1:] are 2. Each step shrinks the unknown region by one and keeps the invariant:
- Swapping a 0 to
lowmoves a known 1 (or the same element when low equals mid) tomid, so both pointers can advance. - Swapping a 2 to
highbrings in an unknown value, somidmust stay and check it.
When the unknown region is empty, the list is sorted.
Complexity
O(n) time, one pass, O(1) extra space.
Code
def sort_colors(nums):
"""Dutch national flag: sort a list of 0s, 1s and 2s in one pass, in place.
Invariant: nums[:low] are 0, nums[low:mid] are 1, nums[high+1:] are 2.
"""
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 -= 1 # do not advance mid: the swapped-in value is unchecked
return nums
if __name__ == "__main__":
assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([2, 0, 1]) == [0, 1, 2]
assert sort_colors([]) == []
assert sort_colors([1]) == [1]
assert sort_colors([2, 2, 2]) == [2, 2, 2]
assert sort_colors([2, 1, 0, 0, 1, 2, 0]) == [0, 0, 0, 1, 1, 2, 2]
print("all tests passed")Save as a16_sort_colors.py and run python3 a16_sort_colors.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list. All the same value. Already sorted or reverse sorted. A 2 swapped with another 2 (handled because mid is not advanced).
Pattern
Three-way partitioning. Quicksort uses it to handle many equal keys (elements less than, equal to and greater than the pivot), and it solves "move negatives before positives" style problems.
def sort_colors(nums):
"""Dutch national flag: sort a list of 0s, 1s and 2s in one pass, in place.
Invariant: nums[:low] are 0, nums[low:mid] are 1, nums[high+1:] are 2.
"""
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 -= 1 # do not advance mid: the swapped-in value is unchecked
return nums
if __name__ == "__main__":
assert sort_colors([2, 0, 2, 1, 1, 0]) == [0, 0, 1, 1, 2, 2]
assert sort_colors([2, 0, 1]) == [0, 1, 2]
assert sort_colors([]) == []
assert sort_colors([1]) == [1]
assert sort_colors([2, 2, 2]) == [2, 2, 2]
assert sort_colors([2, 1, 0, 0, 1, 2, 0]) == [0, 0, 0, 1, 1, 2, 2]
print("all tests passed")Single-pass three-pointer partition with the invariant written in the docstring.
Complexity
Time: O(n). Space: O(1). Each iteration either advances mid or moves high left, so the loop runs at most n times.
By level
Fresher: Gives the counting solution and then the three-pointer loop, tracing it on the example. Should be able to trace the three pointers on a short list.
Mid: States the invariant and justifies each pointer move, linking it to quicksort partitioning. Explains why the middle pointer does not advance after a swap with the high end.
Senior: Generalises to k-way partitioning, discusses stability and cache behaviour, and when a counting approach is simpler to maintain. Can state the number of swaps in the worst case.
Key points
- Three regions: 0s before low, 1s between low and mid, 2s after high
- Swap 0s to low and advance both
- Swap 2s to high and do not advance mid
- One pass, O(1) space
- Same idea as three-way quicksort partition
Common mistakes
- Advancing mid after swapping with high
- Using mid < high and missing the last element
- Counting then rewriting when one pass was required
- Forgetting the empty list
Follow-ups
- How does three-way partitioning improve quicksort with many duplicates?
- How would you sort k colours?
- Can you make it stable?
Tips
- Write the invariant before the code
- Explain the asymmetry between the 0 and 2 cases
- Mention counting sort as the two-pass baseline
Evaluation rubric
- Correct one-pass algorithm
- Clear invariant
- Explains why mid does not advance on a 2
- Correct complexity