Given a binary array, sort it in linear time and constant space. The output should print all zeros, followed by all ones.

For example,

Input:  { 1, 0, 1, 0, 1, 0, 0, 1 }
 
Output: { 0, 0, 0, 0, 1, 1, 1, 1 }

Practice this problem

A simple solution would be to count the total number of 0’s present in the array, say k, and fill the first k indices in the array by 0 and all remaining indices by 1.

Alternatively, we can count the total number of 1’s present in the array k and fill the last k indices in the array by 1 and all remaining indices by 0. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

0 0 0 0 0 0 1 1 1 1

Java


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

Python


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
Instead of counting the total number of zeros, if the current element is 0, we can place 0 at the next available position in the array. After all elements in the array are processed, we fill all remaining indices by 1. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

0 0 0 0 0 0 1 1 1 1

Java


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

Python


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
We can also solve this problem in linear time by using the partitioning logic of Quicksort. The idea is to use 1 as a pivot element and make one pass of the partition process. The resultant array will be sorted. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

0 0 0 0 1 1 1 1

Java


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

Python


Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
Exercise:

1. Modify the solution so that all 1’s would come first.

2. Rearrange even and odd numbers in an array in linear time such that all even numbers come before all odd numbers.