Sort Colors Problem
Description
LeetCode Problem 75.
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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3:
Input: nums = [0]
Output: [0]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
- n == nums.length
- 1 <= n <= 300
- nums[i] is 0, 1, or 2.
Solution
Approach: Dutch National Flag (Three Pointers)
Counting the 0s, 1s and 2s and rewriting the array works, but it needs two passes. We can sort in one pass by growing three regions at the same time.
Keep three pointers and this picture of the array:
[ 0 0 0 | 1 1 1 | ? ? ? ? | 2 2 2 ]
^low ^mid ^high
nums[0..low)are all 0,nums[low..mid)are all 1,nums[mid..high]are not looked at yet,nums(high..end]are all 2.
Look at nums[mid] while mid <= high:
- 0: swap it with
nums[low](which is a 1, ormiditself), then move bothlowandmidforward. - 1: it is already in the right region; move
midforward. - 2: swap it with
nums[high]and movehighback.
The detail people get wrong is the 2 case: do not move mid after that swap. The value that came from high has not been looked at yet, so it must be checked in the next step. In the 0 case we can move mid, because the value that came from low is already known to be a 1.
The loop stops when the unknown region is empty, so every element is looked at once.
Complexity: O(n) time and O(1) extra space, where n is the length of nums.
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
low = 0 # nums[:low] are all 0
mid = 0 # nums[low:mid] are all 1
high = len(nums) - 1 # nums[high + 1:] are all 2
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 move mid: the swapped-in value is not checked yet
Now write it from memory
Close the write-up and solve it yourself against the tests.