Quick revision
The short answer
This is a two pointer partition problem. One pointer starts at each end: the left one skips 0s that are already in place, the right one skips 1s that are already in place, and when the left one sits on a 1 and the right one on a 0, one swap fixes both. It is one pass, O(n) time and O(1) space; counting the 0s and rewriting is an equally fast alternative for plain values.
The solution
What it costs
| Approach | Time | Extra space | Moves the elements? |
|---|---|---|---|
Brute force: Arrays.sort | O(n log n) | O(log n) | yes |
| Count the 0s, then rewrite | O(n), two passes | O(1) | no, writes new values |
| Two pointers working inward | O(n), one pass | O(1) | yes |
What to remember
We sorted an array of 0s and 1s in one pass with two pointers working inward, like two helpers sorting cups from opposite ends: the left pointer skips 0s, the right pointer skips 1s, and a 1 on the left meeting a 0 on the right is fixed with one swap. It runs in O(n) time and O(1) space, beating the O(n log n) of a general sort because we know the values in advance. Counting the 0s and rewriting is equally fast for plain values, and the same loop handles any two-way split. The clue to remember is an in-place split into two groups: that is a two pointer partition.
1What the question asks, told as a shelf of cups
Picture a long shelf with a row of cups, some white and some black, all mixed up. You want every white cup on the left and every black cup on the right, and you have a friend to help. You stand at the left end and your friend at the right end. You walk right past every white cup, since those are already on the correct side. Your friend walks left past every black cup. When you stop at a black cup and your friend stops at a white one, you simply trade cups, and both carry on. When the two of you meet, the shelf is done. That is the whole solution, and the rest of the article makes it precise.
In programming words, we are given an int array whose elements are all 0 or 1, in any order. We must rearrange it so that every 0 comes before every 1, and do it in O(n) time. O(n), read as order n, means the work grows in step with the length n of the array, so twice as long means about twice the work.
We will use one example all the way through, [1, 0, 1, 1, 0, 0, 1, 0], which must become [0, 0, 0, 0, 1, 1, 1, 1]. Let us do the cup method by hand. You start on index 0, which holds 1, a black cup, so you stop. Your friend starts on index 7, which holds 0, a white cup, so your friend stops. Trade: index 0 becomes 0 and index 7 becomes 1. Keep going the same way and you will find only two more trades are needed.
This problem can look like a sorting question, and sorting sounds like heavy machinery. It is much smaller than that. There are only two kinds of value, so we never need to decide which of two numbers is bigger, only which side each one belongs on.
Top row: the array we are given. Bottom row: the same four 0s and four 1s with every 0 first.
- zeros
- 4
- ones
- 4
1The input [1, 0, 1, 1, 0, 0, 1, 0] holds four 0s and four 1s. The answer [0, 0, 0, 0, 1, 1, 1, 1] keeps the same values, 0s first.
What to assume
- May we change the array in place?
- We assume yes.
- Is it guaranteed to hold only 0s and 1s?
- We assume so.
- Are the values plain numbers, or flags on larger records whose other data must move with them?
- Plain numbers here.
- Must equal elements keep their original order?
- For plain 0s and 1s that has no meaning, since one 0 cannot be told from another.
A careful candidate asks a few questions first. May we change the array in place? We assume yes. Is it guaranteed to hold only 0s and 1s? We assume so. Are the values plain numbers, or flags on larger records whose other data must move with them? Plain numbers here, and we come back to records in the follow-ups. Must equal elements keep their original order? For plain 0s and 1s that has no meaning, since one 0 cannot be told from another.
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
A beginner reading the word sort usually reaches for Arrays.sort, the library method, and that is a sensible instinct. Then the phrase in O(n) time appears, and doubt creeps in, because the beginner may remember that sorting costs O(n log n). The question is telling us that the general tool is more than we need. Let us look at the clues one at a time.
The first clue is the phrase only 0s and 1s. Every element belongs to one of two groups, and the result is just the first group followed by the second. Rearranging an array into two groups like this is called partitioning, from the word part: we split the array into a part of 0s and a part of 1s.
The second clue is the time limit, O(n), together with the fact that the work happens inside the array. We may look at each element a small, fixed number of times, and we should not build a second array. So we want something that walks through the array once, deciding as it goes.
These clues point to the two pointers pattern. A pointer here is just an index variable that marks a position in the array, like your finger resting on one cup. Two pointers means we keep two such indexes and move them by simple rules, here one from each end towards the middle. The rule to carry to new problems is this. To split an array in place into two groups, let one pointer grow the first group from the left and another grow the second group from the right, and swap whenever both pointers rest on elements that belong on the other side. The same skeleton separates even numbers from odd ones, negatives from positives, and is the partition step inside quicksort.
A close cousin, also called two pointers, moves both indexes forward: one reads every element and the other marks where the next 0 should be written, as in the move zeroes problem. It also works here, and keeps the original order of the elements it moves, at the cost of more writes. A sliding window does not fit, because we are not looking for a run of neighbours, and binary search does not fit, because the array is not sorted.
3The brute force, and counting as a middle step
The honest first attempt is to call the library and let it sort. It is one line and it is correct, so as a brute force it is a fine thing to mention first.
The counting method reads the array once to count the 0s, then writes the answer over it.
- zeros
- 4
- reads
- 8
1The first pass reads all eight cells and counts the 0s at indexes 1, 4, 5 and 7, so zeros = 4.
- zeros
- 4
- writes
- 8
2The second pass writes 0 into the first four cells and 1 into the rest. The values are right, but they are new values, not the old elements moved.
But let us see what it costs. Arrays.sort is a comparison sort, one that learns the order only by comparing pairs of values. Such a sort cannot assume anything about the values, so in general it needs about n log n comparisons, written O(n log n). Where is the waste? The general sort keeps asking whether one value is bigger than another, though we already know the answer from the problem: every 0 is smaller than every 1.
So here is a natural middle step. Count the 0s in one pass, say there are z of them, then write 0 into the first z positions and 1 into the rest. On our example the first pass reads eight cells and finds z = 4, and the second pass writes eight cells. That is O(n) time and O(1) extra space, and it is a perfectly good answer. The picture shows its two passes.
A beginner may well ask why we need anything better than counting. The answer is in what counting does. It never moves an element; it throws the old values away and writes new ones. For plain numbers that makes no difference. But if each 0 or 1 is a flag on a larger record, such as an order marked paid or unpaid, writing a new 0 does not carry the rest of the order along. The two pointer method swaps the real elements, so it works for records too, and it does the job in a single pass.
4Getting to one pass with two pointers working inward
Let us turn the cup method into exact rules. We keep left, starting at index 0, and right, starting at the last index. We promise ourselves that everything before left is 0 and everything after right is 1. At the start both promises are true, because there is nothing before left and nothing after right. The part from left to right is still unsorted, and each step must shrink it.
At each step we look at a[left] first. If it is 0, it already belongs in the 0 part, so we move left forward by one, and the promise still holds. Otherwise a[left] is 1, and we look at a[right]. If it is 1, it already belongs in the 1 part, so we move right back by one. If neither moved, then a[left] is 1 and a[right] is 0, both on the wrong side. One swap fixes both: we write 0 at left and 1 at right, and move both pointers inward.
Here is the question a beginner usually asks. Why can we write 0 and 1 directly, instead of swapping with a temporary variable as we normally would? Because we know exactly what the two values are. a[left] is 1 and a[right] is 0, so after a swap a[left] must be 0 and a[right] must be 1. Writing those two values is the swap.
When do we stop? We loop while left < right. When left reaches right, at most one element is left in the unsorted middle, and a single element is never out of order with itself. Every step moves at least one pointer, so the middle shrinks every time and the loop must end. And because both promises hold after every step, when the loop ends every element is either a 0 before left or a 1 after right, or the one element where they met, which is fine wherever it is.
The mistake beginners most often make here is to write two inner while loops, one moving left past 0s and one moving right past 1s, without checking left < right inside them. On an array of all 0s, the left loop then runs off the end of the array. Checking only one end per step, as our rules do, keeps every step simple and every index inside the array.
5Watching the two pointers meet
The picture runs the real loop on our example. Each frame shows the array after one step. The settled parts are marked done: the 0s to the left of left and the 1s to the right of right. The two cells under the pointers are the ones the next step will look at.
Watch the settled parts grow from both ends towards the middle, by one or two cells each step, until they touch.
left and right are the two pointers. Cells marked done are settled: 0s on the left of left, 1s on the right of right.
- left
- 0
- right
- 7
- swaps
- 0
1left starts at index 0 and right at index 7. Nothing is known yet. a[left] is 1 and a[right] is 0, so both sit on a value that belongs at the other end.
- step
- 1
- saw
- a[0]=1, a[7]=0
- action
- swap, both move
- left, right
- 1, 6
- swaps
- 1
2In step 1, a[left] is 1 and a[right] is 0, both on the wrong side. One swap fixes both: we write 0 at index 0 and 1 at index 7, then move both inward.
- step
- 2
- saw
- a[1]=0
- action
- left++
- left, right
- 2, 6
- swaps
- 1
3In step 2, a[left] is 0, already in the zone of 0s, so left simply steps forward to index 2.
- step
- 3
- saw
- a[2]=1, a[6]=1
- action
- right--
- left, right
- 2, 5
- swaps
- 1
4In step 3, a[left] is 1, so left must wait. We look at a[right], which is 1 and already in the zone of 1s, so right steps back to index 5.
- step
- 4
- saw
- a[2]=1, a[5]=0
- action
- swap, both move
- left, right
- 3, 4
- swaps
- 2
5In step 4, a[left] is 1 and a[right] is 0 again, so we swap them, writing 0 at index 2 and 1 at index 5, and move both inward.
- step
- 5
- saw
- a[3]=1, a[4]=0
- action
- swap, both move
- left, right
- 4, 3
- swaps
- 3
6In step 5, a[3] is 1 and a[4] is 0, the last wrong pair. We swap them, and left moves to 4 while right moves to 3.
- steps
- 5
- swaps
- 3
- result
- [0, 0, 0, 0, 1, 1, 1, 1]
7Now left is 4 and right is 3, so left < right is false and the loop stops. Everything before index 4 is 0 and everything from 4 on is 1.
Let us read the important frames back. The very first step is a swap, because index 0 holds a 1 and index 7 holds a 0, exactly the cups you and your friend would trade. After it, both ends are settled.
Steps 2 and 3 show the two quieter moves. In step 2, a[left] is 0, so left just steps past it. In step 3, a[left] is 1 and must wait, but a[right] is 1 and already in place, so right steps back.
Steps 4 and 5 are swaps again, each fixing one 1 on the left and one 0 on the right. After step 5, left is 4 and right is 3; they have crossed, so the loop stops. Five steps and three swaps sorted eight elements, and no element was looked at more than twice.
6The complete Java program
Here is the full program, with the two pointer method and the counting method side by side. main sorts our example with the two pointers, an array of only 1s, and a short array with the counting method, and each comment shows what that line prints.
Let us read sortBinary in the order it runs. The first line sets left to 0 and right to a.length - 1, the two ends. The while loop runs as long as left < right, meaning at least two elements remain in the unsorted middle.
Inside, the if checks a[left] == 0 first. If it is true, left++ moves past a 0 that is already in place. The else if runs only when a[left] is 1, and checks a[right] == 1; if it is true, right-- moves past a 1 that is already in place. The final else runs only when a[left] is 1 and a[right] is 0, so it writes 0 and 1 into those cells and moves both pointers inward.
Because exactly one branch runs per step, and every branch moves at least one pointer, the loop always makes progress. So main prints [0, 0, 0, 0, 1, 1, 1, 1] for the example, and [1, 1, 1] for the array of 1s, where right simply walks down to left without a single swap.
sortByCount is the counting method. The loop counts the 0s. Then Arrays.fill(a, 0, zeros, 0) writes 0 into positions from 0 up to, but not including, zeros, and Arrays.fill(a, zeros, a.length, 1) writes 1 into the rest. So [1, 0, 0, 1, 0] becomes [0, 0, 0, 1, 1].
7How much it costs, and the cases at the edges
Let us count on the example first. The pointers start 7 apart, at indexes 0 and 7. A swap closes the gap by 2 and a single move by 1, so after three swaps and two single moves the gap has closed by 3 times 2 plus 2, which is 8, and the pointers have crossed. Five steps for eight elements. In general the pointers start n - 1 apart and each step closes the gap by at least 1, so there are at most n - 1 steps, and the time is O(n). We use two index variables and nothing else, so the space is O(1).
The counting method reads the array once and writes it once, about 2n steps, which is also O(n) time and O(1) space. The library sort does about n log n comparisons, so for large arrays both linear methods win clearly.
| Approach | Time | Extra space | Moves the elements? |
|---|---|---|---|
Brute force: Arrays.sort | O(n log n) | O(log n) | yes |
| Count the 0s, then rewrite | O(n), two passes | O(1) | no, writes new values |
| Two pointers working inward | O(n), one pass | O(1) | yes |
The edge cases need no special code. For an empty array, right starts at -1, so left < right is false and the loop never runs. For a single element, left and right are both 0, so again the loop never runs. An array of only 1s just moves right down to left, and an array of only 0s moves left up to right, both with no swaps.
One limit is worth saying aloud. The swap can change the order of records that share the same flag. With plain 0s and 1s nobody can notice, but for records that must keep their order we need a stable method, which the follow-ups cover.
8Follow-up questions
How do you extend this to 0s, 1s and 2s?
That is the Dutch national flag problem. We keep three indexes. low marks the end of the 0 part, mid is the element being looked at, and high marks the start of the 2 part. If a[mid] is 0, we swap it with a[low] and move both low and mid forward. If it is 1, it is already in the middle, so we just move mid. If it is 2, we swap it with a[high] and move high back, but we do not move mid, because the value that just arrived from high has not been looked at yet. The loop runs while mid <= high, in one pass with O(1) space.
What if the 0s and 1s are flags on records, and the order within each group must be kept?
Then we need a stable partition, one that keeps records with the same flag in their original order. Doing that in place and in linear time is hard, so we use a second array. One pass copies the records flagged 0, in order, and a second pass appends the records flagged 1, in order. That is O(n) time and O(n) space. The two pointer swap would not do, because it can jump a record over others with the same flag.
How would you separate even and odd numbers?
With exactly the same loop. We replace the test a[left] == 0 with a[left] % 2 == 0, and a[right] == 1 with a[right] % 2 != 0. The one real change is the swap. The values are no longer just 0 and 1, so we cannot write them directly; we swap a[left] and a[right] with a temporary variable. Any split into two groups by a yes or no question works this way.
9Conclusion
We sorted an array of 0s and 1s in one pass with two pointers working inward, like two helpers sorting cups from opposite ends: the left pointer skips 0s, the right pointer skips 1s, and a 1 on the left meeting a 0 on the right is fixed with one swap. It runs in O(n) time and O(1) space, beating the O(n log n) of a general sort because we know the values in advance. Counting the 0s and rewriting is equally fast for plain values, and the same loop handles any two-way split. The clue to remember is an in-place split into two groups: that is a two pointer partition.
Open with
Let me confirm I can change the array in place and that it holds only zeros and ones. The brute force is Arrays.sort, which is O(n log n), more than we need since we know the values.
Then, if they want more
One linear answer is to count the zeros and rewrite the array, but that writes new values instead of moving elements, so I will use the two pointer partition, which also works if the zeros and ones were flags on records. left starts at index zero and right at the last index.
Everything before left is zero and everything after right is one.
While left is less than right: if a of left is zero, it is in place, so left moves forward; else if a of right is one, it is in place, so right moves back; otherwise left is on a one and right is on a zero, so I write zero at left and one at right and move both inward.
Each step moves at least one pointer, so there are at most n steps: O(n) time and O(1) space. An empty array or a single element never enters the loop, and all zeros or all ones finish without a swap. With twos as well, I would use the Dutch national flag method with three pointers.
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 27 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 "Given an array holding only 0s and 1s, sort it in O(n) time.": https://scrivio-interview-library.netlify.app/data-structures/solutions/given-an-array-holding-only-0s-and-1s-sort-it-in-o-n-time-8b03b4/