15% off all plans & roadmaps Use code
See plansSort Colors
- LeetCode 75
- Medium
- Two Pointers
- In-place Array Modification
Updated
TL;DR: Sort an array of 0s, 1s and 2s in place without a library sort. Keep three pointers that split the array into a 0 zone, a 2 zone and an unknown middle, and sort it in one pass with O(1) extra space.
Problem
You are given an array nums with n objects colored red, white, or blue. Sort the array in place so that objects of the same color sit next to each other, ordered red, then white, then blue.
The integers 0, 1, and 2 stand for red, white, and blue. You must solve the problem without calling the library 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]
Constraints
n == nums.length1 <= n <= 300nums[i]is either0,1, or2.
Constraints that matter
nums[i]is only 0, 1 or 2. With three possible values you do not need a comparison sort. Counting or partitioning beats O(n log n).- The array must be sorted in place. Building a second sorted array is not allowed, so you need swaps or overwrites inside
nums. nis at most 300, so even an O(n^2) bubble sort passes. The limit is small on purpose, so the interview is about whether you spot the three-value structure.nis at least 1, so you never receive an empty array. A single element is already sorted and every loop must handle it without an index error.
Hints
Hint 1
The pattern is two pointers with in-place partitioning.
Hint 2
Treat the problem as plain sorting and write bubble sort.
Solution
Intuition
The pattern is two pointers with in-place partitioning. Look at the values: only three exist. A general sort compares elements against each other, but here every element can be classified on its own. A 0 belongs at the front, a 2 belongs at the back, and a 1 belongs in between.
Picture a clerk sorting a line of coats into two racks at the ends and a pile in the middle. The low pointer is the next free spot on the front rack, and high is the next free spot on the back rack.
That suggests splitting the array into four zones: finished 0s on the left, finished 1s next, an unknown zone, and finished 2s on the right. You keep a pointer at each border. Every step looks at one unknown element and moves it across a border, which shrinks the unknown zone by one.
This works because the borders only move in one direction and each move settles one element for good. Nothing is ever revisited once it sits in a finished zone. That gives one pass and no extra memory.
The one subtle part is what you swap in. When you send a 2 to the back, the element you pull from the back is unknown. You must inspect it before moving on. When you send a 0 to the front, the element you pull from the front is always a 1 or the same cell, so it is already classified.
Worked example
Input: nums = [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2] Explanation: The array holds two 0s, two 1s and two 2s. After sorting in place, both 0s come first, then both 1s, then both 2s.
Approach 1: Brute force: repeated adjacent swaps
Treat the problem as plain sorting and write bubble sort. Scan the array, and whenever a neighbor pair is out of order, swap it. Repeat the full scan until a scan makes no swaps.
This is correct for any values, which is why a beginner reaches for it. It ignores that only three values exist.
Steps
- Set a flag
swappedto true to enter the loop. - Reset
swappedto false at the start of each scan. - Walk
ifrom 0 to n - 2 and comparenums[i]withnums[i + 1]. - If
nums[i]is larger, swap the two and setswappedto true. - Stop when a full scan finishes with no swaps.
Dry run
Trace on [2,0,2,1,1,0]. Each line is the array after one full scan.
- Scan 1:
[0,2,1,1,0,2]. The last 2 bubbled to the end. - Scan 2:
[0,1,1,0,2,2]. - Scan 3:
[0,1,0,1,2,2]. - Scan 4:
[0,0,1,1,2,2]. - Scan 5: no swaps happen, so the loop stops with
[0,0,1,1,2,2].
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Here n is the array length, and each scan costs n - 1 comparisons. Every swap removes exactly one inversion (an out-of-order pair), and an array has at most n * (n - 1) / 2 inversions, so the number of scans is at most n. That gives O(n^2) time. Only a few integer variables are used, so space is O(1).
PythonTested in our runner
from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
n = len(nums)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
swapped = True
JavaTested in our runner
import java.util.*;
class Solution {
public void sortColors(int[] nums) {
int n = nums.length;
boolean swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < n - 1; i++) {
if (nums[i] > nums[i + 1]) {
int tmp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = tmp;
swapped = true;
}
}
}
}
};C++Tested in our runner
using namespace std;
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i + 1 < n; i++) {
if (nums[i] > nums[i + 1]) {
swap(nums[i], nums[i + 1]);
swapped = true;
}
}
}
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {void}
*/
var sortColors = function(nums) {
const n = nums.length;
let swapped = true;
while (swapped) {
swapped = false;
for (let i = 0; i < n - 1; i++) {
if (nums[i] > nums[i + 1]) {
[nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
swapped = true;
}
}
}
};GoTested in our runner
func sortColors(nums []int) {
n := len(nums)
swapped := true
for swapped {
swapped = false
for i := 0; i < n-1; i++ {
if nums[i] > nums[i+1] {
nums[i], nums[i+1] = nums[i+1], nums[i]
swapped = true
}
}
}
}C#Tested in our runner
public class Solution {
public void sortColors(int[] nums) {
int n = nums.Length;
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < n - 1; i++) {
if (nums[i] > nums[i + 1]) {
int tmp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = tmp;
swapped = true;
}
}
}
}
}Approach 2: Counting sort, two passes
What's slow: bubble sort compares neighbors again and again and moves values one cell at a time. It pays for generality the input does not need.
The insight that fixes it: with only three values, the sorted array is fully described by how many 0s, 1s and 2s exist. Count them in one pass, then overwrite the array from the left with that many 0s, then 1s, then 2s.
Steps
- Create
counts = [0, 0, 0]. - Pass 1: for each value
xinnums, incrementcounts[x]. - Set a write index
idxto 0. - Pass 2: for each color
cfrom 0 to 2, writecintonums[idx]and advanceidx, repeatingcounts[c]times. - Return with no value, since
numsis already updated.
Dry run
Trace on [2,0,2,1,1,0].
- Pass 1 reads each value: counts go
[0,0,1],[1,0,1],[1,0,2],[1,1,2],[1,2,2],[2,2,2]. - Pass 2 writes two 0s into indices 0 and 1, two 1s into indices 2 and 3, and two 2s into indices 4 and 5.
- The array becomes
[0,0,1,1,2,2], which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. Pass 1 touches each element once, and pass 2 writes each of the n cells exactly once, so total work is 2n, which is O(n). The counts array has three cells no matter how large n gets, so extra space is O(1). It uses two passes, which is why the follow-up asks for something tighter.
PythonTested in our runner
from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
counts = [0, 0, 0]
for x in nums:
counts[x] += 1
idx = 0
for color in range(3):
for _ in range(counts[color]):
nums[idx] = color
idx += 1
JavaTested in our runner
import java.util.*;
class Solution {
public void sortColors(int[] nums) {
int[] counts = new int[3];
for (int x : nums) {
counts[x]++;
}
int idx = 0;
for (int color = 0; color < 3; color++) {
for (int k = 0; k < counts[color]; k++) {
nums[idx++] = color;
}
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void sortColors(vector<int>& nums) {
int counts[3] = {0, 0, 0};
for (int x : nums) {
counts[x]++;
}
int idx = 0;
for (int color = 0; color < 3; color++) {
for (int k = 0; k < counts[color]; k++) {
nums[idx++] = color;
}
}
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {void}
*/
var sortColors = function(nums) {
const counts = [0, 0, 0];
for (const x of nums) {
counts[x]++;
}
let idx = 0;
for (let color = 0; color < 3; color++) {
for (let k = 0; k < counts[color]; k++) {
nums[idx++] = color;
}
}
};GoTested in our runner
func sortColors(nums []int) {
counts := [3]int{}
for _, x := range nums {
counts[x]++
}
idx := 0
for color := 0; color < 3; color++ {
for k := 0; k < counts[color]; k++ {
nums[idx] = color
idx++
}
}
}C#Tested in our runner
public class Solution {
public void sortColors(int[] nums) {
int[] counts = new int[3];
foreach (int x in nums) {
counts[x]++;
}
int idx = 0;
for (int color = 0; color < 3; color++) {
for (int k = 0; k < counts[color]; k++) {
nums[idx++] = color;
}
}
}
}
Solution pattern
In-place Array Modification
Part of Two Pointers
Approach 3: One-pass three pointers (Dutch national flag)OptimalIn-place Array Modification
What's slow: counting sort reads the data once and then rewrites it in a second pass. The counts throw away the elements, so you must rebuild them from scratch.
The insight that fixes it: place each element into its final zone the moment you see it. Keep low as the next cell for a 0, high as the next cell for a 2, and mid as the element under inspection. Cells before low are 0s, cells from low up to mid - 1 are 1s, and cells after high are 2s. Cells from mid to high are unknown.
Why it is correct. The loop keeps one invariant: cells before low hold 0s, cells from low to mid minus one hold 1s, and cells after high hold 2s. Each step either grows a finished zone or shrinks the unknown range while keeping that invariant true. When mid passes high, every cell is classified, so the array is sorted.
Steps
- Set
low = 0,mid = 0,high = n - 1. - Loop while
mid <= high. - If
nums[mid]is 0, swap it withnums[low], then increment bothlowandmid. - If
nums[mid]is 1, leave it and incrementmid. - If
nums[mid]is 2, swap it withnums[high]and decrementhigh. Do not movemid, because the swapped-in value is unchecked. - When
midpasseshigh, the unknown zone is empty and the array is sorted.
Dry run
Trace on [2,0,2,1,1,0], with n = 6. The array column shows the state after the step.
| Step | low | mid | high | nums[mid] | Action | Array after |
|---|---|---|---|---|---|---|
| start | 0 | 0 | 5 | 2 | swap with index 5, high-- | [0,0,2,1,1,2] |
| 1 | 0 | 0 | 4 | 0 | swap with itself, low++, mid++ | [0,0,2,1,1,2] |
| 2 | 1 | 1 | 4 | 0 | swap with itself, low++, mid++ | [0,0,2,1,1,2] |
| 3 | 2 | 2 | 4 | 2 | swap with index 4, high-- | [0,0,1,1,2,2] |
| 4 | 2 | 2 | 3 | 1 | mid++ | [0,0,1,1,2,2] |
| 5 | 2 | 3 | 3 | 1 | mid++ | [0,0,1,1,2,2] |
| end | 2 | 4 | 3 | - | mid > high, stop | [0,0,1,1,2,2] |
In the first row the 0 from index 5 landed at mid and was handled on the next step, which is why mid waits after a 2. The final array matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. Every loop iteration either increases mid by one or decreases high by one, and the loop ends when they cross. The gap high - mid + 1 starts at n and shrinks by one each iteration, so there are at most n iterations of constant work. Only three integer pointers are stored, so space is O(1).
PythonTested in our runner
from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
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:
# the value from high is unchecked, so mid stays
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
JavaTested in our runner
import java.util.*;
class Solution {
public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
int tmp = nums[low];
nums[low] = nums[mid];
nums[mid] = tmp;
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
// the value from high is unchecked, so mid stays
int tmp = nums[high];
nums[high] = nums[mid];
nums[mid] = tmp;
high--;
}
}
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
void sortColors(vector<int>& nums) {
int low = 0, mid = 0, high = (int)nums.size() - 1;
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums[low], nums[mid]);
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
// the value from high is unchecked, so mid stays
swap(nums[mid], nums[high]);
high--;
}
}
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {void}
*/
var sortColors = function(nums) {
let low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
[nums[low], nums[mid]] = [nums[mid], nums[low]];
low++;
mid++;
} else if (nums[mid] === 1) {
mid++;
} else {
// the value from high is unchecked, so mid stays
[nums[mid], nums[high]] = [nums[high], nums[mid]];
high--;
}
}
};GoTested in our runner
func sortColors(nums []int) {
low, mid, high := 0, 0, len(nums)-1
for mid <= high {
if nums[mid] == 0 {
nums[low], nums[mid] = nums[mid], nums[low]
low++
mid++
} else if nums[mid] == 1 {
mid++
} else {
// the value from high is unchecked, so mid stays
nums[mid], nums[high] = nums[high], nums[mid]
high--
}
}
}C#Tested in our runner
public class Solution {
public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.Length - 1;
while (mid <= high) {
if (nums[mid] == 0) {
int tmp = nums[low];
nums[low] = nums[mid];
nums[mid] = tmp;
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else {
// the value from high is unchecked, so mid stays
int tmp = nums[high];
nums[high] = nums[mid];
nums[mid] = tmp;
high--;
}
}
}
}Common mistakes
- Writing
mid += 1after swapping withhigh. The value that arrives from the back has never been inspected and may be a 0. Keepmidin place and only decrementhigh. - Using
while mid < highas the loop condition. Whenmid == high, one unknown cell is still left. Usemid <= high. - Forgetting
low += 1after the 0 case. The 0 zone never grows, and the next 0 overwrites the one you placed earlier. Advance bothlowandmid. - Not advancing
midin the 0 case. The swapped-in value fromlowis always a 1 (or the same cell), so it is already classified. Skippingmid += 1makes the loop revisit it. - Initializing
high = len(nums)instead oflen(nums) - 1. The first swap then reads past the end of the array. Start at the last valid index. - Calling
nums.sort()or building a new list and returning it. The problem bans the library sort and wantsnumschanged in place. A new list assigned to a local name leaves the caller's array untouched.
Edge cases
[0]: a single element is already sorted. The loop runs once, incrementslowandmid, and exits.[2,2,2]: every step is a swap tohigh.highfalls to -1 and the array is unchanged.[0,0,0]or[1,1,1]: only one color. Pointers sweep through without moving data in a harmful way.[2,1,0]: fully reversed. The first step swaps 2 and 0 to give[0,1,2], then the 1 and the 2 are accepted in place.[1,0]and[1,2]: two elements with a 1 first. Check thatmiddoes not run pasthighafter the 1 is skipped.- Already sorted input such as
[0,1,2]: the algorithm still completes in one pass and leaves the array as is.
Follow-ups interviewers ask
- Can you do it in one pass with constant extra space?
- Yes, that is the three-pointer approach. Each iteration moves exactly one element into its final zone, so you read the array once and use three integers. Counting sort needs two passes because it reads first and writes second.
- What if there were k colors instead of 3?
- Counting sort generalizes with a counts array of size k, giving O(n + k) time and O(k) space. A one-pass in-place partition for more than three colors does not extend cleanly with a single swap rule. You can run the three-way partition recursively, or use a standard sort in O(n log n).
- Why does swapping with
lownever bring in an unchecked value? - Everything from
lowup tomid - 1has already been inspected and is a 1. So whenlowis behindmid,nums[low]is a 1. Whenlowequalsmid, you swap a cell with itself. In both cases the value moving tomidneeds no further check, somidcan advance.
Sort Colors FAQ
What is the time complexity of Sort Colors?
The one-pass three-pointer solution runs in O(n) time and O(1) space. Each loop iteration either advances mid or retreats high, and they meet after at most n iterations. Bubble sort is O(n^2) and counting sort is O(n) with two passes.
Why use two pointers for Sort Colors?
Two pointers at the ends of the unknown region let you place 0s at the front and 2s at the back with one swap each. A third pointer scans the middle. This sorts the three values in a single pass without extra memory.
Can Sort Colors be solved in O(1) extra space?
Yes. Both counting sort (three counters) and the three-pointer partition use constant extra space. Only the three-pointer version does it in a single pass.
Why does mid not move when nums[mid] is 2?
The swap pulls an unseen value from the high end into mid. That value could be a 0, 1 or 2. You need to examine it on the next iteration, so mid stays put.
Is the Sort Colors solution in Python different from Java?
The logic is identical. Python swaps with tuple assignment, Java uses a temporary variable. Neither language has an overflow risk here because values are only 0, 1 or 2.
Why is this called the Dutch national flag algorithm?
The three zones of 0s, 1s and 2s resemble the three bands of the Dutch flag. Dijkstra described the partitioning problem with that name. LeetCode 75 is a direct application of it.
Asked at
See which companies ask this — Pro
Related problems
- String Compression · same technique: In-place Array Modification
- Remove Duplicates from Sorted Array II · same technique: In-place Array Modification
- Move Pieces to Obtain a String · same technique: In-place Array Modification
- Separate Black and White Balls · same technique: In-place Array Modification
- Trapping Rain Water · same technique: In-place Array Modification
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers