Sort a binary array (containing only 0s and 1s) in a single pass. This is the two-color variant of the Dutch National Flag problem: partition all 0s to the left and all 1s to the right in-place.
This problem reduces to a single-pass partition: maintain a write pointer z that tracks the position to place the next 0. Iterate once and swap when you see a 0. The algorithm is in-place and stable with O(1) extra space.
We only need to separate two values (0 and 1). Maintain a pointer z (index of next zero slot). As we scan with index i, when arr[i] == 0 we swap it into position z and increment z. This keeps all zeros on the left in one pass.
#include<vector>using std::vector;
classSolution {
public:void sortBinaryArray(vector<int>& arr) {
int n = arr.size();
int z =0;
for (int i =0; i < n; ++i) {
if (arr[i] ==0) {
std::swap(arr[i], arr[z]);
++z;
}
}
}
};
import java.util.List;
import java.util.Collections;
publicclassSolution {
publicvoidsortBinaryArray(int[] arr) {
int n = arr.length;
int z = 0;
for (int i = 0; i < n; ++i) {
if (arr[i]== 0) {
int tmp = arr[i];
arr[i]= arr[z];
arr[z]= tmp;
++z;
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funsortBinaryArray(arr: IntArray) {
var z = 0for (i in arr.indices) {
if (arr[i] ==0) {
val tmp = arr[i]
arr[i] = arr[z]
arr[z] = tmp
z++ }
}
}
}
1
2
3
4
5
6
7
8
9
10
from typing import List
classSolution:
defsortBinaryArray(self, arr: List[int]) ->None:
n: int = len(arr)
z: int =0for i in range(n):
if arr[i] ==0:
arr[i], arr[z] = arr[z], arr[i]
z +=1
1
2
3
4
5
6
7
8
9
10
11
12
13
pubstructSolution;
impl Solution {
pubfnsort_binary_array(arr: &mut [i32]) {
letmut z: usize=0;
for i in0..arr.len() {
if arr[i] ==0 {
arr.swap(i, z);
z +=1;
}
}
}
}