Sort Colors
Sort an array of 0s, 1s and 2s in place and in one pass, with the three pointers of the Dutch flag method.
The problem
You get an array nums where every value is 0, 1 or 2, standing for the colors red, white and blue. Sort it in place so that all 0s come first, then all 1s, then all 2s, without calling a library sort. The function returns nothing.
Input nums = [1, 2, 0, 1, 2, 0, 0]
Output [0, 0, 0, 1, 1, 2, 2]
Three 0s, then two 1s, then two 2s.
Input nums = [2, 2, 1]
Output [1, 2, 2]
With no 0s, the single 1 simply moves to the front.
Key constraint: Sort in place; the follow-up asks for a single pass with O(1) extra space.
How to spot the pattern
- There are only three different values, and each one belongs in a known zone of the array.
- You must rearrange in place in one pass, so pointers have to mark the zone boundaries as you go.
The idea
Keep three zones while you scan: everything before low is 0, everything after high is 2, and everything from low to mid - 1 is 1. Look at nums[mid]: a 0 gets swapped down to low, a 2 gets swapped up to high, and a 1 is already in the right zone. When mid passes high, every value has reached its zone.
Brute force: Call a general sort in O(n log n), or count the 0s, 1s and 2s and rewrite the array, which is O(n) but takes two passes.
Step by step
- 1Set
low = 0,mid = 0andhigh = n - 1. - 2While
mid <= high, look atnums[mid]. - 3If it is 0, swap it with
nums[low]and move bothlowandmidforward. - 4If it is 1, just move
midforward. - 5If it is 2, swap it with
nums[high]and movehighback, but leavemidwhere it is, because the value that just arrived fromhighhasn't been checked yet.
See the pattern move
The two pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def sortColors(self, nums: List[int]) -> None:
# nums[:low] are 0s, nums[low:mid] are 1s, nums[high + 1:] are 2s
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 # the swapped-in value is still uncheckedComplexity
Time
O(n)
Space
O(1)
Each step either moves mid forward or moves high back, so there are at most n steps.
Watch out for
- Moving
midforward after swapping withhigh: the value that came from the right is unchecked and might be a 0 or a 2. - Looping while
mid < high, which leaves the element athighunchecked.
Follow-up questions
Why is it safe to move mid forward after swapping with low?
Everything from low to mid - 1 is a 1, or that range is empty and low == mid. Either way, the value coming back from low has already been checked and belongs in the middle zone.
What if there were k different colors?
Counting works for any small k in O(n + k), using two passes. The one-pass partition only splits into three groups at a time; for more colors you can repeat it, peeling off the smallest and largest color each round.
In Hinglish
Teen zone banao: low ke peeche 0, high ke aage 2, beech mein 1. 2 wale swap ke baad mid ko aage mat badhao, naya number abhi check nahi hua.