Quick revision
The short answer
Sorting an array of 0s, 1s and 2s in one pass is a two pointers problem, the Dutch national flag partition. Three indexes, low, mid and high, keep 0s before low, 1s from low to mid - 1 and 2s after high; mid looks at each unknown value, sending a 0 left and a 2 right by swapping. Each round shrinks the unknown region by one, so 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 rewrite | O(n) | 2 | O(1) |
| Three pointers, low, mid and high | O(n) | 1 | O(1) |
What to remember
We sorted an array of 0s, 1s and 2s in one pass with three pointers. Everything before low is 0, everything from low to mid - 1 is 1, everything after high is 2, and mid looks at the first unknown value: a 0 swaps left and both pointers move on, a 1 just moves mid, and a 2 swaps right while mid stays, because the newcomer is unchecked. The unknown region shrinks by one each round, so it is O(n) time and O(1) space. The clue to remember is an in-place split into a few groups: keep one pointer per boundary and say what each region holds.
1What the question asks, told as a shelf of books
Imagine a librarian standing in front of a single shelf of books. Each spine is red, white or blue, and the colours are all mixed up. She is asked to group them: every red book on the left, every white book in the middle, every blue book on the right. She has no spare table to put books on, so the only move she can make is to swap two books on the shelf. And she is in a hurry, so she wants to walk along the shelf only once.
The question is that shelf with numbers. The array holds only the values 0, 1 and 2, standing for the three colours, and we must rearrange it in place, meaning inside the same array, so that all 0s come first, then all 1s, then all 2s. Single pass means we walk along the array once. The problem is often called the Dutch national flag problem, after the three bands of that flag.
Let us take [2, 0, 2, 1, 1, 0] and think by hand. There are two 0s, two 1s and two 2s, so the answer must be [0, 0, 1, 1, 2, 2]. Doing it with swaps, the first 2 should go to the right end and the last 0 to the left end, so swapping those two already helps a great deal. The question is how to choose swaps so that one walk is always enough, whatever the starting order.
Top row: the array we are given. Bottom row: the same values after sorting, 0s first, then 1s, then 2s.
1The six values 2, 0, 2, 1, 1, 0 must become 0, 0, 1, 1, 2, 2, using swaps inside the same array and one walk along it.
What to assume
- Must we sort in place?
- Yes, we change the given array and return nothing.
- What does single pass mean exactly?
- One walk from left to right, with only a few extra variables.
- Can a value be missing entirely, such as no 1s at all?
- Yes, and the method must still work.
- Can the array be empty or have one element?
- Yes, and nothing should change.
- Could other values appear?
- No, the question promises only 0, 1 and 2.
A careful candidate asks a few questions first. Must we sort in place? Yes, we change the given array and return nothing. What does single pass mean exactly? One walk from left to right, with only a few extra variables. Can a value be missing entirely, such as no 1s at all? Yes, and the method must still work. Can the array be empty or have one element? Yes, and nothing should change. Could other values appear? No, the question promises only 0, 1 and 2.
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 partition with pointers
When a beginner first reads this question, the word sort suggests reaching for Arrays.sort, and that is a correct answer. But it ignores the most important fact in the question, that there are only three different values. When a question tells us something that strong about the data, it usually expects us to use it.
Let us take the clues one at a time. The first is only 0s, 1s and 2s. With three known values we never need to compare two elements with each other, as a general sort does. For each element we only need to know which of three groups it belongs to, so sorting here really means splitting the array into three groups, which is called partitioning.
The second clue is the phrase in place, or no extra array. Then the array itself must hold everything we know. The usual way to do that is to keep a few indexes that mark where each group begins and ends, and to grow the groups by swapping elements across those marks.
The third clue is single pass. We cannot count first and write later. Each element must be sent to its group the moment we look at it, which means the group boundaries must move as we go.
These clues point to the two pointers pattern. A pointer here is simply an index variable that marks a position in the array, like a bookmark on the shelf. In the two pointers pattern, a few such indexes move through the array and divide it into regions, each with a known meaning. With two groups, two pointers are enough, as when moving all zeros to one side; with three groups we need three, called low, mid and high. The rule to carry to new problems is to keep one pointer per boundary between groups and to state what each region holds.
Some ideas look similar and do not fit. Counting sort, which counts each value and rewrites the array, is fast but needs two passes. A hash map of counts is counting sort with more machinery. The two pointers that start at both ends and meet in the middle, used for pair sums in a sorted array, move by comparing a sum, which has no meaning here.
3The honest first attempt, sorting or counting
The first answer anyone gives is Arrays.sort(a), which is correct and costs O(n log n) time for n elements, the price of a general sort. A better brute force uses the three values. We walk the array once to count how many 0s, 1s and 2s there are, and then walk it again, writing that many 0s, then that many 1s, then that many 2s.
Let us do it by hand. The first walk reads 2, 0, 2, 1, 1, 0 and counts two 0s, two 1s and two 2s. The second walk writes 0, 0, 1, 1, 2, 2. That is six reads and six writes, two walks of the array. For n elements it is 2n steps, so the time is O(n), read as order n, and the count array has three places whatever n is, so the extra space is O(1), constant.
So the counting brute force is already fast. Where is the weakness? It walks the array twice, and the question asks for once. And it does not move the elements, it overwrites them. With plain numbers that is harmless, but if each element were a whole record, say an order with a priority field of 0, 1 or 2, writing back the numbers would lose the orders. Swapping moves the records themselves, which is what the librarian does with real books. So we want to place each element in its group the moment we read it.
4Getting to the one-pass partition, one observation at a time
Let us imagine the array, at any moment of the walk, split into four regions, like four stretches of the librarian's shelf. From index 0 up to low - 1 is a block of 0s. From low up to mid - 1 is a block of 1s. From mid up to high is the part we have not looked at yet. From high + 1 to the end is a block of 2s. At the start, low and mid are 0 and high is the last index, so the three blocks are empty and everything is unknown.
Now take one step. We look at a[mid], the first unknown value. If it is 1, it is already in the right place, at the end of the 1 block, so we just move mid on. If it is 0, we swap it with a[low], the first cell of the 1 block, so the 0 block grows by one and the 1 block shifts one place right. Then we move both low and mid on. If it is 2, we swap it with a[high], the last unknown cell, and move high back by one, so the 2 block grows from the right.
Here a beginner usually asks the question that matters most. After a swap with high, why do we not move mid on as well, as we do for the other two cases? Let us try it and see what happens, on the small array [1, 2, 0].
The array [1, 2, 0]. The third frame is the mistake; the last two frames show the correct rule, where mid stays put.
- low
- 0
- mid
- 1
- high
- 2
1We start with low = 0, mid = 0 and high = 2. a[mid] is 1, so mid moves to 1 and the 1 block holds one cell.
- low
- 0
- mid
- 1
- high
- 1
2a[mid] is 2, so it swaps with a[high]. The 0 from the end arrives at index 1, and high moves to 1. Nobody has looked at that 0 yet.
- low
- 0
- mid
- 2
- high
- 1
- result
- wrong
3Suppose we also move mid on. Now mid is 2 and high is 1, so the loop stops, and the unchecked 0 is stuck after a 1: [1, 0, 2] is wrong.
- low
- 0
- mid
- 1
- high
- 1
4The real rule keeps mid at 1 after the swap, so mid <= high is still true and the new value under mid gets looked at.
- low
- 1
- mid
- 2
- high
- 1
- result
- right
5It is a 0, so it swaps with a[low], and the 1 moves to index 1. low becomes 1, mid becomes 2, and the array is [0, 1, 2].
The picture shows the answer. The value that arrives at mid after a swap with high came from the unknown region, so nobody has looked at it yet. It could be a 0, a 1 or a 2. If we move past it, an unchecked 0 can be left stranded in the 1 block, as [1, 0, 2] shows. So after a swap with high, mid stays where it is, and the next round looks at the newcomer.
Then why is it safe to move mid on after a swap with low? Because the value that comes back from a[low] is the first cell of the 1 block, which we have already looked at and know is a 1. When the 1 block is empty, low and mid are the same cell, and the 0 simply swaps with itself. Either way, what lands under mid is known, so moving on is safe.
Why does this always sort the array? Every round either moves mid forward or moves high back, so the unknown region shrinks by exactly one each round and the loop ends after n rounds. Each case keeps the four regions true. When mid passes high, the unknown region is empty, so the array is 0s, then 1s, then 2s. A description that stays true at every step, like our four regions, is called an invariant, and saying it aloud is the best way to explain this code in an interview.
5Watching low, mid and high sort the example
The picture plays the loop on [2, 0, 2, 1, 1, 0]. Under the cells are the three pointers. Cells marked as finished are in a final block, either before mid, where the 0s and 1s are, or after high, where the 2s are. The marked cell is under mid and is the next one to be looked at. The panel shows the three pointers and how many unknown cells are left.
Watch the unknown count fall by exactly one in every frame, and watch mid stand still after each swap with high.
Finished cells are already in their final block. The cell under mid is the one we look at next; everything from mid to high is still unknown.
- low
- 0
- mid
- 0
- high
- 5
- unknown
- 6 cells
1At the start low and mid are 0 and high is 5. Nothing is known yet, so the whole array is the unknown region from mid to high.
- low
- 0
- mid
- 0
- high
- 4
- unknown
- 5 cells
2a[mid] is 2, so we swap it with a[high], the last unknown cell, and move high to 4. The 0 that came back to mid has not been checked, so mid stays.
- low
- 1
- mid
- 1
- high
- 4
- unknown
- 4 cells
3a[mid] is now 0, so we swap it with a[low]. Here low and mid are the same cell, so the 0 swaps with itself. low and mid both move to 1.
- low
- 2
- mid
- 2
- high
- 4
- unknown
- 3 cells
4a[mid] is 0 again and low equals mid once more, so it swaps with itself. low and mid move to 2. The 0 block now holds two cells.
- low
- 2
- mid
- 2
- high
- 3
- unknown
- 2 cells
5a[mid] is 2, so it swaps with a[high], index 4, which holds 1. high moves to 3, and the 1 that came back waits under mid to be checked.
- low
- 2
- mid
- 3
- high
- 3
- unknown
- 1 cells
6a[mid] is 1, which belongs exactly where the 1 block ends, so we only move mid to 3. No swap is needed.
- low
- 2
- mid
- 4
- high
- 3
- unknown
- 0 cells
7a[mid] is 1 again, so mid moves to 4. Now mid is past high, the unknown region is empty, and the loop stops: [0, 0, 1, 1, 2, 2].
Let us read the important frames back. In the second frame a 2 goes to the end, and the 0 that came back stays under mid, because it is unchecked. In the third and fourth frames that 0, and the next one, swap with themselves, because the 1 block is still empty, so low and mid move together and nothing visibly changes.
In the fifth frame the second 2 swaps with the 1 at index 4, and high moves to 3. Again mid stays, and in the sixth frame it finds the 1 and simply moves on. In the last frame mid is 4 and high is 3, so mid has passed high, the unknown region is empty, and the loop ends.
Count the rounds. There were six, one for each element, and four swaps, two of them swaps of a cell with itself. The librarian walked the shelf once.
6The complete Java program
Here is the whole program. The comment above the method states the four regions, the invariant, because the rest of the code is just keeping it true. main sorts the example, the array [1, 2, 0] from the picture of the mistake, a single element and the empty array, and each comment shows what the line prints.
Let us read sortColors in the order it runs. First low and mid are set to 0 and high to the last index, a.length - 1, so the whole array is unknown. The loop runs while mid <= high, that is, while at least one cell is still unknown. The test uses <= because when mid equals high exactly one cell is unknown and still needs a look.
Inside the loop we look at a[mid]. For a 0, swap(a, low++, mid++) swaps the two cells and then moves both pointers on. The ++ after a variable means the old value is used for the swap and the variable grows by one afterwards. For a 1 we only write mid++. For a 2, swap(a, mid, high--) swaps a[mid] with a[high] and then moves high back, and mid is left alone because the newcomer is unchecked.
The swap helper is the usual three lines with a temporary variable t, so that neither value is lost while the other is copied over it.
In main, [1, 2, 0] prints [0, 1, 2], which shows the rule about mid working on the very case that broke the wrong version. [1] is looked at once and left alone. For the empty array high starts at -1, so mid <= high is false at once and the loop never runs.
7How much it costs, and the cases at the edges
Let us count on the example first. The loop ran six rounds for six elements, with at most one swap per round. In general every round shrinks the unknown region by one, so there are exactly n rounds and the time is O(n), in a single pass. The method keeps three indexes and one temporary variable, whatever n is, so the extra space is O(1).
The table compares the three approaches. Counting has the same order of time, but it walks the array twice and rewrites values instead of moving elements.
| Approach | Time | Passes | Extra space |
|---|---|---|---|
Arrays.sort | O(n log n) | many | O(log n) |
| Count, then rewrite | O(n) | 2 | O(1) |
| Three pointers, low, mid and high | O(n) | 1 | O(1) |
The edge cases need no special code. The empty array has high = -1, so the loop never runs. A single element is looked at once and stays. A missing value, such as no 1s, just leaves one block empty, and the regions still hold. An array that is already sorted still takes one pass, swapping each 0 with itself and moving past the 1s, and a reversed array such as [2, 1, 0] is handled by the same three rules.
Two tempting mistakes are worth naming once more. One is moving mid on after a swap with high. The other is writing mid < high in the loop test, which leaves the last unknown cell unchecked. In [2, 0, 1], for example, the loop with < would stop with a 0 after a 1.
8Follow-up questions
Why does mid not move on after swapping with high, when it does after swapping with low?
Because of where the newcomer comes from. After a swap with high, the value arriving at mid came from the unknown region, so it may be a 0, a 1 or a 2, and we must look at it in the next round. After a swap with low, the value arriving at mid came from the start of the 1 block, so we already know it is a 1, or it is the same 0 when low equals mid. Known values can be passed; unknown ones cannot.
How does this relate to quick sort?
It is the three-way partition that quick sort uses when there are many equal values. Values smaller than the pivot go left, values equal to it stay in the middle, and larger values go right. With the pivot 1, that is exactly 0s, 1s and 2s. Three-way partitioning keeps quick sort from slowing to O(n^2) on arrays full of duplicates, because all the equal values are finished in one go.
What if there were k different values instead of three?
For a small k, counting is the simplest answer, O(n + k) time in two passes. If the elements must be moved in place, we can partition once per value, which is O(n x k), or apply quick sort style partitioning on the range of values, which is O(n log k). The one-pass three pointer trick is special to three groups, because there are only two ends to send values to.
9Conclusion
We sorted an array of 0s, 1s and 2s in one pass with three pointers. Everything before low is 0, everything from low to mid - 1 is 1, everything after high is 2, and mid looks at the first unknown value: a 0 swaps left and both pointers move on, a 1 just moves mid, and a 2 swaps right while mid stays, because the newcomer is unchecked. The unknown region shrinks by one each round, so it is O(n) time and O(1) space. The clue to remember is an in-place split into a few groups: keep one pointer per boundary and say what each region holds.
Open with
The array holds only zeros, ones and twos, and I sort it in place in one pass. Arrays.sort works in n log n, and counting each value then rewriting is linear but takes two passes and overwrites elements.
Then, if they want more
For one pass I use the Dutch national flag partition, a two pointers pattern with three pointers because there are three groups. I keep low, mid and high, with the invariant that everything before low is zero, low to mid minus one is one, after high is two, and mid to high is unknown.
While mid is at most high I look at a of mid. A zero swaps with a of low and both low and mid move on, because what comes back is a known one. A one just moves mid on.
A two swaps with a of high and high moves back, but mid stays, because the value that arrived has not been checked. Each round shrinks the unknown region by one, so it is O(n) time and constant space. Empty arrays, single elements and missing values all work because regions may be empty.
About this answer
- Last updated
- 14 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 19 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 containing only 0s, 1s and 2s in a single pass.": https://scrivio-interview-library.netlify.app/data-structures/solutions/sort-an-array-containing-only-0s-1s-and-2s-in-a-single-pass-467038/