Problem
Section titled “Problem”You are given an array nums with n objects coloured red, white, or blue. Sort them in-place so that objects of the same colour are adjacent, with the colours in the order red, white, and blue.
We use the integers 0, 1, and 2 to represent the colours 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]Explanation: The array has two 0s, two 1s and two 2s; sorted in place the 0s come first, then the 1s, then the 2s.Example 2:
Input: nums = [2,0,1]Output: [0,1,2]Constraints:
n == nums.lengthnums[i]is either0,1, or2.
Follow-up: Could you come up with a one-pass algorithm using only constant extra space?
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”A counting sort (count the 0s, 1s and 2s, then overwrite the array) already runs in , but it needs two passes. The follow-up asks for one.
Because there are only three values, we can instead grow three bands at the same time while scanning once — the Dutch national flag partition. Keep three pointers so that at every moment:
| Range | Contents |
|---|---|
[0, lo) | all 0 |
[lo, mid) | all 1 |
[mid, hi] | not yet examined |
(hi, n) | all 2 |
Look at nums[mid] and move it into the band it belongs to. The unknown region shrinks by one element at each step, so the scan ends after at most n steps.
Algorithm
Section titled “Algorithm”- Set
lo = 0,mid = 0,hi = n - 1. - While
mid <= hi:- If
nums[mid] == 0: swapnums[lo]andnums[mid], then increment bothloandmid. The value swapped in fromlois a1(or it is the same cell), so it is safe to step past it. - If
nums[mid] == 1: it is already in the middle band; incrementmid. - If
nums[mid] == 2: swapnums[mid]andnums[hi], then decrementhi. Do not advancemid: the value that came fromhihas not been examined yet.
- If
Walkthrough
Section titled “Walkthrough”Green cells are final, blue is the element being examined:
Complexity
Section titled “Complexity”- Time: — each iteration either advances
midor decrementshi, so there are at mostniterations, all in a single pass. - Space: — three indices.
Edge cases
Section titled “Edge cases”- Single element or all the same colour: the loop only moves
mid(or onlyhi) and the array is left unchanged. - Already sorted / reverse sorted: handled identically; no special casing is needed.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: void sortColors(vector<int>& nums) { int lo = 0, mid = 0, hi = (int)nums.size() - 1; while (mid <= hi) { if (nums[mid] == 0) { swap(nums[lo++], nums[mid++]); } else if (nums[mid] == 1) { mid++; } else { swap(nums[mid], nums[hi--]); } } }};class Solution { public void sortColors(int[] nums) { int lo = 0, mid = 0, hi = nums.length - 1; while (mid <= hi) { if (nums[mid] == 0) { swap(nums, lo++, mid++); } else if (nums[mid] == 1) { mid++; } else { swap(nums, mid, hi--); } } }
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }}class Solution: def sortColors(self, nums: list[int]) -> None: lo, mid, hi = 0, 0, len(nums) - 1 while mid <= hi: if nums[mid] == 0: nums[lo], nums[mid] = nums[mid], nums[lo] lo += 1 mid += 1 elif nums[mid] == 1: mid += 1 else: nums[mid], nums[hi] = nums[hi], nums[mid] hi -= 1Give it a try first
Attempt the problem on LeetCode — the code will still be here.
![Dutch national flag partition on [2,0,2,1,1,0], step 1 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/01.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 2 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/02.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 3 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/03.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 4 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/04.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 5 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/05.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 6 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/06.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 7 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/07.webp)
![Dutch national flag partition on [2,0,2,1,1,0], step 8 of 8](/CodePrime/img/codes/sort-colors/dutch-flag/08.webp)