Quick revision
The short answer
Sorting an array of 0s, 1s and 2s in one pass is a two pointer partition problem, known as the Dutch national flag. Three indexes keep 0s before low, 1s from low to mid, 2s after high and the unknown part between mid and high; a 0 is swapped to low, a 1 is passed over, and a 2 is swapped to high without moving mid. It takes O(n) time and O(1) space.
The solution
What it costs
| Approach | Time | Passes | Extra space |
|---|---|---|---|
Arrays.sort | O(n log n) | many | O(log n) |
| Count, then overwrite | O(n) | two | O(1) |
| Dutch national flag partition | O(n) | one | O(1) |
What to remember
We sorted an array of 0s, 1s and 2s in one pass with three indexes. Before low are the 0s, from low to mid the 1s, after high the 2s, and between mid and high the unknown part. A 0 is swapped to low and both move, a 1 just moves mid, and a 2 is swapped to high while mid waits to check the new arrival. It takes O(n) time and O(1) space. The clue to remember is a fixed, small number of groups, in place and in one pass: give each group boundary a pointer and swap each element into its group.
1What it means to sort three kinds of values in one pass
Picture a long narrow tray holding a row of balls in three colours, red, white and blue. The tray is so narrow that you cannot lift balls out and put them aside; the only thing you may do is swap two balls. Your job is to finish with all the reds on the left, all the whites in the middle and all the blues on the right, and to do it walking along the tray only once. That is this problem exactly, with 0 for red, 1 for white and 2 for blue.
In Java terms we are given an int array holding only 0, 1 and 2, and we must rearrange it in place, meaning inside the same array without making a second one, into 0s, then 1s, then 2s. Single pass means we walk through the array once, deciding about each element as we meet it.
We keep one example for the whole article, the array {1, 2, 0, 2, 1, 0}. It holds two of each value, so the answer is {0, 0, 1, 1, 2, 2}. The interesting part is how a program reaches it with swaps, in one walk, without looking ahead.
Top row: the array we are given. Bottom row: the same six values after sorting, 0s, then 1s, then 2s.
1The top row is the input {1, 2, 0, 2, 1, 0}. The bottom row is the answer, the same values with the two 0s first, then the 1s, then the 2s.
What to assume
- Can other values appear?
- No; if one does, our code throws an exception rather than misplacing it silently. The values it has already passed may have been moved by then, so the array should not be used after that exception.
- Can the array be empty, or hold only one value?
- Yes, and it must come out unchanged.
- Are the elements plain ints, or objects that carry a colour along with other data?
- Plain ints here.
This problem can look like a full sorting question, but it is much smaller than that. There are only three possible values, so every element already knows where it belongs, the front, the middle or the back. All we need is a tidy way of remembering how far the front and the back have filled up.
A careful candidate asks a few questions first. Can other values appear? No; if one does, our code throws an exception rather than misplacing it silently. The values it has already passed may have been moved by then, so the array should not be used after that exception. Can the array be empty, or hold only one value? Yes, and it must come out unchanged. Are the elements plain ints, or objects that carry a colour along with other data? Plain ints here, but the answer matters for one of the brute force ideas, as we will see.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a two pointer partition problem
When a beginner reads this question, the word sort jumps out, and the natural move is to call Arrays.sort. That is a fine first answer and our brute force. But the question says more than sort, and the extra words are the clues.
The first clue is the phrase only the values 0, 1 and 2. A general sort compares elements with each other because it does not know where anything belongs. Here we know in advance: every 0 goes to the front and every 2 goes to the back. When each element's destination is known from its value alone, we do not need comparisons between elements at all. We only need to put each element into its group.
The second clue is in a single pass, together with sort an array, which means in place. One pass means we decide about each element when we first look at it. In place means the groups must grow inside the array itself. So we need some markers in the array that say where the 0s end and where the 2s begin, and those markers must move as the groups grow.
Those markers are what the two pointers pattern is about. A pointer here is not a special Java feature; it is simply an int variable holding an index, like a finger resting on one box of the array. The pattern uses two or more such fingers that move through the array according to simple rules, so that one walk does the work. Moving elements into groups with pointers that mark the group boundaries is called partitioning, from the word partition, a wall that divides a room.
This particular problem is famous as the Dutch national flag problem, because the Dutch flag has three stripes, and sorting three colours into three stripes is the picture its inventor, Edsger Dijkstra, had in mind. The general rule to carry away is this. When elements must be moved into a fixed number of groups in one pass, keep one pointer per group boundary, and make every step move one element into its group with a swap while the boundaries move.
Some ideas look similar but do not fit. Two pointers coming from both ends to find a pair with a given sum need sorted data and move by comparing sums, not by group. Counting sort uses the three values well, but it rewrites values and needs two passes.
3The honest first attempt, sorting or counting
The first solution anyone writes is a library call, Arrays.sort(a). It is short and correct, so it is a perfectly good place to start. A better idea, and a good middle step, is to count how many 0s, 1s and 2s there are, and then write that many of each back into the array.
Let us count the library sort first. Arrays.sort on ints uses a quicksort that takes about n log n steps, where log n is the number of times n can be halved before reaching 1. For a million elements that is about 20 million steps, so the time is O(n log n), read as order n log n. It compares elements whose places we could have told from their values.
Now the counting version by hand. The first pass over {1, 2, 0, 2, 1, 0} finds two 0s, two 1s and two 2s, so count is [2, 2, 2]. The second pass writes 0, 0, then 1, 1, then 2, 2. That is 6 steps for counting and 6 for writing, 12 in all, so the time is O(n), and the extra space is O(1), constant, because three counters are enough whatever the size of the array.
Counting is a good answer to mention, but it has two weaknesses. It walks the array twice, and the question asks for one pass. More importantly, it does not move elements, it overwrites them. If each element were an object, say an order with a priority of 0, 1 or 2, writing back the number 0 would lose the order itself.
So where is the waste? Look at the moment the first pass reads the 0 at index 2. At that very moment we already know where it belongs, at the front. The first pass throws that knowledge away and keeps only a number, and the second pass has to come back for it. So let us ask the question that leads further. If we already know where a 0 or a 2 belongs the moment we see it, can we put it there straight away, with a swap?
4Getting to the Dutch national flag partition, one observation at a time
Go back to the tray of balls. Suppose we walk along it from the left. Every time we meet a red ball, we want it at the front, so we keep a finger, low, on the first place after the reds we have already gathered, and swap the red there. Every time we meet a blue ball, we want it at the back, so we keep a finger, high, on the last place before the blues we have gathered, and swap the blue there. A white ball is already where whites belong if all the whites seen so far sit just behind the reds. Our walking finger is called mid.
So at every moment the array is cut into four parts by the three fingers. Indexes before low hold only 0s. Indexes from low up to mid - 1 hold only 1s. Indexes after high hold only 2s. And indexes from mid to high are still unknown, not yet looked at. A promise like this, which is true before and after every step, is called an invariant. At the start low and mid are 0 and high is the last index, so the first three parts are empty and everything is unknown, which keeps the promise trivially.
Each step looks at a[mid] and makes the unknown part one smaller. If a[mid] is 1, it already sits right after the 1s, so we just move mid forward. If a[mid] is 0, we swap it with a[low], then move both low and mid forward. If a[mid] is 2, we swap it with a[high] and move high back.
Now comes the question nearly every beginner asks. Why does mid move after a 0 but not after a 2? They look like mirror images. Let us look at what arrives at mid in each case. After swapping with low, the value that comes to mid was at index low, which is the first of the 1s region, so we already know it is a 1, and it is exactly where 1s belong. After swapping with high, the value that comes to mid was at index high, inside the unknown part. It might be 0, 1 or 2, and nobody has looked at it yet. If mid moved on, that value would be skipped forever.
When the 1s region is empty, low and mid are equal, and the 0 rule swaps a[mid] with itself. That is harmless, and it saves us an if.
Why does the loop end with a sorted array? Every step either moves mid forward or moves high back, so the unknown part shrinks by one each time and the loop runs at most n times. It stops when mid passes high, because then the unknown part is empty. The invariant still holds, so the array is 0s, then 1s, then 2s, and it took exactly one walk.
The mistake a beginner is most likely to make is writing the loop condition as mid < high instead of mid <= high. It is tempting because most loops use a strict less-than. But when mid equals high, one element is still unknown, and skipping it can leave a 0 or a 2 in the wrong place.
5Watching the three fingers sort the example
The picture plays the loop on {1, 2, 0, 2, 1, 0}, using the arrays the Java method produced after each step. Under the cells are the three indexes low, mid and high. Settled cells, the ones outside the unknown part, are marked as done; the cell mid is about to look at is marked as now; and cells that were just swapped are marked as compared.
As you step through, watch when mid moves and when it waits.
The cells left of mid and right of high are settled. mid looks at one unknown cell per step; a swapped-in 2 sends a new value to mid, which is checked before mid moves.
- low
- 0
- mid
- 0
- high
- 5
- a[mid] seen
- none yet
- action
- start
1We start with low and mid on index 0 and high on index 5. Nothing is settled yet, so the whole array is the unknown part.
- low
- 0
- mid
- 1
- high
- 5
- a[mid] seen
- 1
- action
- mid++
2a[mid] is 1, and a 1 belongs right after the 1s we already have, so we only move mid to index 1. The settled part is now [1].
- low
- 0
- mid
- 1
- high
- 4
- a[mid] seen
- 2
- action
- swap 1,5
3a[mid] is 2, so we swap it with a[high], sending the 2 to the back, and move high to 4. mid stays, because the 0 that arrived is unchecked.
- low
- 1
- mid
- 2
- high
- 4
- a[mid] seen
- 0
- action
- swap 0,1
4a[mid] is 0, so we swap it with a[low]. The 1 from the front moves to index 1, the 0 joins the 0s, and both low and mid move forward.
- low
- 2
- mid
- 3
- high
- 4
- a[mid] seen
- 0
- action
- swap 1,2
5a[mid] is 0 again. We swap it with a[low], which holds the 1 we placed earlier, and move low and mid on. The 0s are 0, 0 and the 1s are 1.
- low
- 2
- mid
- 3
- high
- 3
- a[mid] seen
- 2
- action
- swap 3,4
6a[mid] is 2, so we swap it with a[high], which holds a 1, and move high to 3. mid stays on index 3 to check the 1 that just arrived.
- low
- 2
- mid
- 4
- high
- 3
- a[mid] seen
- 1
- action
- mid++
7a[mid] is 1, so we move mid to 4. Now mid has passed high, the unknown part is empty, and the array reads 0, 0, 1, 1, 2, 2.
Let us read the important frames back. In the second frame a 1 is found and only mid moves, because a 1 at the front with no 0s yet is still in the right region. In the third frame the 2 at index 1 is swapped to the back, and a 0 arrives at index 1. mid stays on it, which is exactly the point of the rule, because that 0 has not been looked at yet.
In the fourth frame that 0 is swapped with a[low], and the 1 from index 0 moves to index 1. Now we can see why mid may move after a 0: what arrived at mid is the 1 we had already seen. The fifth frame does the same for the second 0.
The sixth frame swaps the last 2 to index 4, and a 1 arrives at index 3, unchecked, so mid waits once more. In the last frame that 1 is accepted, mid moves to 4, which is past high at 3, and the loop stops after six steps, one per element.
6The complete Java program
Here is the full program. A switch with arrow labels keeps the three cases side by side. main sorts our example, the classic example {2, 0, 2, 1, 1, 0}, an array that starts with two 2s, an array of only 1s and an empty array, and each comment shows what that line prints.
Let us read sort012 in the order it runs. The first line sets low and mid to 0 and high to the last index, so everything starts unknown, and the loop runs while at least one element is still unknown.
Inside, the switch looks at a[mid]. For a 0, swap(a, low++, mid++) swaps a[low] and a[mid] and then moves both indexes forward; a ++ after a variable means use its current value first, then add one. For a 1, mid++ is all we need. For a 2, swap(a, mid, high--) sends the 2 to the back and moves high back, and mid stays. Any other value reaches default and throws. We do not check the whole array in a separate pass first, so the elements handled before the bad one stay where the loop put them.
When mid passes high, the loop ends with the array sorted in place. In main, both examples print [0, 0, 1, 1, 2, 2]. For {2, 2, 0}, the first swap sends a 2 to the back and brings the 0 to the front, where mid checks it before moving on, giving [0, 2, 2]. The array of 1s only moves mid, and the empty array starts with high at -1, so the loop never runs and it prints [].
7How much it costs, and the cases at the edges
Let us count on the example first. The loop ran six times for six elements, because each step moved mid forward or high back. For n elements it runs exactly n times, with at most one swap each, so the time is O(n), in one pass.
The only extra memory is three indexes and the temporary variable inside swap, so the space is O(1).
| Approach | Time | Passes | Extra space |
|---|---|---|---|
Arrays.sort | O(n log n) | many | O(log n) |
| Count, then overwrite | O(n) | two | O(1) |
| Dutch national flag partition | O(n) | one | O(1) |
The edge cases need no special code. An empty array has high = -1, so the loop never starts. A single element is looked at once and stays put. An array of all 0s swaps each element with itself; all 1s only move mid; all 2s swap each one to the back. An array already sorted or sorted backwards is handled by the same invariant.
One property is worth knowing. The algorithm is not stable, which means two equal values may end up in a different order from the one they started in. For plain ints nobody can tell, but for objects that must keep their original order among equals, counting into a second array, or a stable sort, is the better choice.
8Follow-up questions
Why does mid advance after swapping a 0 but not after swapping a 2?
Think about where the arriving value came from. After swapping with low, the value that comes to mid was at index low, the first place of the 1s region, so it is a 1 we have already looked at, or, when low equals mid, it is the 0 itself. Either way it is settled, so mid can move on. After swapping with high, the value that comes to mid was in the unknown part and could be anything, so mid must stay and look at it on the next step.
How does this relate to quicksort?
Quicksort picks a value called the pivot and splits the array into smaller values on the left and larger on the right, then sorts each side. When many elements equal the pivot, a two-way split handles them badly. The Dutch national flag gives a three-way split, smaller, equal and larger, with 1 playing the pivot. Quicksort that uses it puts all the equal elements in their final place at once and stays fast on inputs with many duplicates.
What if there were four values, 0 to 3, instead of three?
The idea extends, but it gets fiddly. We could run the three-way partition twice: first treat 0 as small, 1 and 2 as middle and 3 as large, then partition the middle region again into 1s and 2s. That is still O(n) time and O(1) space, though no longer one pass. For many distinct values, counting sort or a general sort is simpler and clearer.
9Conclusion
We sorted an array of 0s, 1s and 2s in one pass with three indexes. Before low are the 0s, from low to mid the 1s, after high the 2s, and between mid and high the unknown part. A 0 is swapped to low and both move, a 1 just moves mid, and a 2 is swapped to high while mid waits to check the new arrival. It takes O(n) time and O(1) space. The clue to remember is a fixed, small number of groups, in place and in one pass: give each group boundary a pointer and swap each element into its group.
Open with
Let me confirm the input first: only 0, 1 and 2, sorted in place, and the question asks for a single pass. Arrays.sort works in O(n log n) but ignores that there are only three values.
Then, if they want more
Counting the 0s, 1s and 2s and writing them back is O(n), but it takes two passes and overwrites values rather than moving elements. So I will use the Dutch national flag partition. I keep three indexes, low and mid starting at 0 and high at the last index.
The invariant is that everything before low is 0, everything from low to mid minus one is 1, everything after high is 2, and mid to high is unknown. While mid is at most high, I look at a[mid]. A 0 is swapped with a[low] and both move forward, because what comes back is an already-seen 1.
A 1 just moves mid. A 2 is swapped with a[high] and high moves back, but mid stays, because the value that arrives has not been checked. Each step shrinks the unknown part by one, so it is O(n) time, one pass, and O(1) space.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 41 times in that collection. How it is counted
- Official documentation
- Arrays (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Sort an array that holds only the values 0, 1 and 2 in a single pass.": https://scrivio-interview-library.netlify.app/data-structures/solutions/sort-an-array-that-holds-only-the-values-0-1-and-2-in-a-single-p-2feacf/
Coding patterns, question 3 of 15 Back to the path
More two pointers questions