Sort Colors solution explained
Sort Colors, sorting an array that holds only 0, 1 and 2 in place, is solved in one pass with three pointers, the Dutch national flag partition. Keep 0s before low, 1s between low and mid, and 2s after high. Look at nums[mid]: swap a 0 to low and advance both, step past a 1, or swap a 2 to high and shrink high without advancing mid. It runs in O(n) time with O(1) extra space.
By Evin JohnPublished 7 min read
What the problem asks
An array holds only the values 0, 1 and 2, which stand for three colours. Rearrange it in place so that all 0s come first, then all 1s, then all 2s. Library sort functions are off the table. The usual follow-up asks for a single pass with constant extra memory.
| Before | After |
|---|---|
| [2, 0, 1, 2, 0, 1] | [0, 0, 1, 1, 2, 2] |
| [2, 2, 0] | [0, 2, 2] |
| [0, 1, 0] | [0, 0, 1] |
| [1] | [1] |
Why this question
Sort Colors is a partition problem in disguise. The interviewer wants to see you notice that a general sort is overkill for three values, reach for counting, and then, when asked for one pass, maintain a three-region invariant without off-by-one errors. The same three-way partition powers quicksort on data with many repeated keys, so it is a useful idea to own beyond this problem.
Follow-ups
- k colours instead of three. Counting generalizes directly in O(n + k). A one-pass partition does not; for many colours, counting is the practical answer.
- Sort objects by a colour field, keeping equal colours in their original order. The three-pointer swap is not stable. Use counting with a second array, which is a stable counting sort.
- Partition around any pivot value. Replace 0, 1 and 2 with less than, equal to and greater than the pivot. This is exactly the step used in quickselect and three-way quicksort.
- Minimize swaps. Count first, then you know the target region of every value and can swap each misplaced value directly.
Two passes: count, then rewrite
Count how many 0s, 1s and 2s there are, then overwrite the array with that many 0s, then 1s, then 2s. It is O(n) time and O(1) space, since the count array has a fixed size of three. Offer it first: it is simple, clearly correct and often all the interviewer needs.
def sort_colors_by_counting(nums):
counts = [0, 0, 0]
for x in nums:
counts[x] += 1
i = 0
for color in range(3):
for _ in range(counts[color]):
nums[i] = color
i += 1One pass with three pointers
Split the array into four regions: 0s at the start up to low, 1s from low up to mid, unknown values from mid to high, and 2s after high. Start with low and mid at 0 and high at the last index, so everything is unknown. Each step looks at nums[mid] and shrinks the unknown region by one. A 0 is swapped to the end of the 0s region, and both low and mid move forward. A 1 is already in the right region, so only mid moves. A 2 is swapped to just before the 2s region, and high moves back, but mid stays, because the value just swapped in came from the unknown region and has not been looked at.
def sort_colors(nums):
low, mid, high = 0, 0, len(nums) - 1
# nums[:low] are 0s, nums[low:mid] are 1s, nums[high + 1:] are 2s,
# and nums[mid:high + 1] is still unsorted.
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 value swapped in is uncheckedWhy can mid advance after a 0 swap? The value that comes back from position low is either a 1, if the 1s region is non-empty, or the same 0 when low equals mid. Either way it is already known and correct. The loop condition is mid <= high, not mid < high, because the value at high is still unknown until mid reaches it.
An overwrite trick in JavaScript
A less common one-pass method never swaps. Read each value, then write a 2 at its position. If the value was below 2, also write a 1 at the end of the 1s region and grow that region. If it was 0, also write a 0 at the end of the 0s region. Later writes overwrite earlier ones in the right order, so the regions stay correct. It is short and makes a good second answer, but the three-pointer version is easier to explain.
function sortColors(nums) {
// Overwrite from the back: every value writes a 2, then a 1 or 0 lands lower.
let zeroEnd = 0; // next slot for a 0
let oneEnd = 0; // next slot for a 1
for (let i = 0; i < nums.length; i++) {
const v = nums[i];
nums[i] = 2;
if (v < 2) nums[oneEnd++] = 1;
if (v < 1) nums[zeroEnd++] = 0;
}
}Comparison
| Approach | Passes | Time | Extra space | Stable for records |
|---|---|---|---|---|
| Library sort | Several | O(n log n) | Depends on the sort | Depends |
| Count, then rewrite | 2 | O(n) | O(1) | Only with a second output array |
| Three pointers | 1 | O(n) | O(1) | No |
| Overwrite trick | 1 | O(n) | O(1) | Only for plain values |
Edge cases
- Empty array: high starts at -1 and the loop never runs.
- Only one colour present.
- Only 0s and 2s, which exercises both swaps without any 1 in between.
- Already sorted, and sorted in reverse.
- A 2 at mid that gets swapped with another 2 from high: high must still move.
Mistakes
- Advancing mid after swapping with high, which leaves an unchecked 0 or 2 in the middle.
- Using mid < high and skipping the last unknown value.
- Starting high at n instead of n - 1.
- Trying to keep the three-pointer version stable for records; it is not.
- Dismissing the counting version as slow because it makes two passes. Two passes is still O(n).
Explaining your solution
Fictional example
- Candidate
- Counting would work in two passes. For one pass, I'll keep four regions: zeros before low, ones from low to mid, unknown from mid to high, twos after high.
- Candidate
- At mid: a zero swaps with low and both move up. A one just moves mid. A two swaps with high and high moves down, but mid stays because I haven't seen the value that came in.
- Candidate
- The unknown region shrinks by one every step, so it's linear, and I only use three indices.
- Interviewer
- Is it stable?
- Candidate
- No. If these were records with a colour field and order mattered, I'd use a counting sort into a second array.
Related problems
Move Zeroes is the two-region version of this partition. The same three-way split is the heart of quickselect in Kth Largest Element in an Array. Subarray Sum Equals K and First Missing Positive are other array problems with a neat linear answer.
Natively for practice sessions
Natively can capture this problem from your screen on Mac or Windows and set out the three-region invariant with code, which is a quick way to check why your version loops or leaves a value unsorted. In mock interviews it keeps a transcript, so you can confirm you explained why mid stays still after the swap with high. Read about Natively for coding interviews.
Questions people ask
What is the Dutch national flag algorithm?
A one-pass partition into three regions with pointers low, mid and high. Values smaller than the middle go before low, equal values stay between low and mid, and larger values go after high.
Why does mid not move after swapping with high in Sort Colors?
The value swapped in from high comes from the unchecked region, so it still has to be examined. After a swap with low, the value coming back is already known, so mid can move.
Can Sort Colors be solved with counting?
Yes. Count the 0s, 1s and 2s, then overwrite the array. It takes two passes, O(n) time and O(1) extra space, and is a good first answer.
Is the Sort Colors partition stable?
No. Swaps can reorder equal values. If you are sorting records by colour and must keep their order, use a counting sort into a separate output array.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
