Segregate 0s and 1s in an array
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array [Basically you have to sort the array]. Traverse array only once.
Input : [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]Input : [0, 1, 0]
Output : [0, 0, 1]Input : [1, 1]
Output : [1, 1]Input : [0]
Output : [0]
Naive Approach – Count 1s and 0s – Two Traversals
Let’s understand with an example we have an array arr = [0, 1, 0, 1, 0, 0, 1] the size of the array is 7 now we will traverse the entire array and find out the number of zeros in the array, In this case the number of zeros is 4 so now we can easily get the number of Ones in the array by Array Length – Number Of Zeros. Once we have counted, we can fill the array first we will put the zeros and then ones (we can get number of ones by using above formula).
#include <iostream>
#include <vector>
using namespace std;
// Function to segregate 0s and 1s
void segregate0and1(vector<int>& arr) {
// Count 0s
int count = 0;
for (int x : arr)
if (x == 0)
count++;
// Fill the vector with 0s until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// Fill the remaining vector space with 1s
for (int i = count; i < arr.size(); i++)
arr[i] = 1;
}
int main() {
vector<int> arr = { 0, 1, 0, 1, 1, 1 };
segregate0and1(arr);
cout << "Array after segregation is ";
for (int x : arr)
cout << x << " ";
return 0;
}
// C code to Segregate 0s and 1s in an array
#include <stdio.h>
// Function to segregate 0s and 1s
void segregate0and1(int arr[], int n)
{
int count = 0; // Counts the no of zeros in arr
for (int i = 0; i < n; i++)
if (arr[i] == 0)
count++;
// Loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// Loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// Function to print segregated array
void print(int arr[], int n)
{
printf("Array after segregation is ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
// Driver function
int main()
{
int arr[] = { 0, 1, 0, 1, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
print(arr, n);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
// Java code to Segregate 0s and 1s in an array
import java.io.*;
public class GFG {
// function to segregate 0s and 1s
static void segregate0and1(int arr[], int n)
{
int count = 0; // counts the no of zeros in arr
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
static void print(int arr[], int n)
{
System.out.print("Array after segregation is ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// driver function
public static void main(String[] args)
{
int arr[] = new int[]{ 0, 1, 0, 1, 1, 1 };
int n = arr.length;
segregate0and1(arr, n);
print(arr, n);
}
}
// This code is contributed by Kamal Rawal
# Python 3 code to Segregate
# 0s and 1s in an array
# Function to segregate 0s and 1s
def segregate0and1(arr, n) :
# Counts the no of zeros in arr
count = 0
for i in range(0, n) :
if (arr[i] == 0) :
count = count + 1
# Loop fills the arr with 0 until count
for i in range(0, count) :
arr[i] = 0
# Loop fills remaining arr space with 1
for i in range(count, n) :
arr[i] = 1
# Function to print segregated array
def print_arr(arr , n) :
print( "Array after segregation is ",end = "")
for i in range(0, n) :
print(arr[i] , end = " ")
# Driver function
arr = [ 0, 1, 0, 1, 1, 1 ]
n = len(arr)
segregate0and1(arr, n)
print_arr(arr, n)
# This code is contributed by Nikita Tiwari.
// C# code to Segregate 0s and 1s in an array
using System;
class GFG {
// function to segregate 0s and 1s
static void segregate0and1(int []arr, int n)
{
// counts the no of zeros in arr
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// loop fills the arr with 0 until count
for (int i = 0; i < count; i++)
arr[i] = 0;
// loop fills remaining arr space with 1
for (int i = count; i < n; i++)
arr[i] = 1;
}
// function to print segregated array
static void print(int []arr, int n)
{
Console.WriteLine("Array after segregation is ");
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// driver function
public static void Main()
{
int []arr = new int[]{ 0, 1, 0, 1, 1, 1 };
int n = arr.Length;
segregate0and1(arr, n);
print(arr, n);
}
}
//This code is contributed by vt_m.
<script>
// JavaScript code to Segregate 0s and 1s in an array
// Function to segregate 0s and 1s
function segregate0and1(arr, n)
{
let count = 0; // Counts the no of zeros in arr
for (let i = 0; i < n; i++) {
if (arr[i] == 0)
count++;
}
// Loop fills the arr with 0 until count
for (let i = 0; i < count; i++)
arr[i] = 0;
// Loop fills remaining arr space with 1
for (let i = count; i < n; i++)
arr[i] = 1;
}
// Function to print segregated array
function print(arr, n)
{
document.write("Array after segregation is ");
for (let i = 0; i < n; i++)
document.write(arr[i] + " ");
}
// Driver function
let arr = [ 0, 1, 0, 1, 1, 1 ];
let n = arr.length;
segregate0and1(arr, n);
print(arr, n);
// This code is contributed by Surbhi Tyagi
</script>
<?php
// PHP code to Segregate
// 0s and 1s in an array
// Function to segregate
// 0s and 1s
function segregate0and1(&$arr, $n)
{
$count = 0; // Counts the no
// of zeros in arr
for ($i = 0; $i < $n; $i++)
{
if ($arr[$i] == 0)
$count++;
}
// Loop fills the arr
// with 0 until count
for ($i = 0; $i < $count; $i++)
$arr[$i] = 0;
// Loop fills remaining
// arr space with 1
for ($i = $count; $i < $n; $i++)
$arr[$i] = 1;
}
// Function to print
// segregated array
function toprint(&$arr , $n)
{
echo ("Array after segregation is ");
for ($i = 0; $i < $n; $i++)
echo ( $arr[$i] . " ");
}
// Driver Code
$arr = array(0, 1, 0, 1, 1, 1 );
$n = sizeof($arr);
segregate0and1($arr, $n);
toprint($arr, $n);
// This code is contributed
// by Shivi_Aggarwal
?>
Output
Array after segregation is 0 0 1 1 1 1
Time Complexity : O(n)
Auxiliary Space: O(1)
The above solution has two issues
- Requires two traversals of the array.
- If 0s and 1s represent keys (say 0 means first year students and 1 means second year) of large objects associated, then the above solution would not work.
Expected Approach – One Traversal
Maintain two indexes. Initialize the first index left as 0 and second index right as n-1.
Do following while lo < hi
…a) Keep incrementing index lo while there are 0s at it
…b) Keep decrementing index hi while there are 1s at it
…c) If lo < hi then exchange arr[lo] and arr[hi]
#include <iostream>
#include <vector>
using namespace std;
/* Function to put all 0s on the left and all 1s on the right */
void segregate0and1(vector<int>& arr) {
// Initialize lo and hi indexes
int lo = 0, hi = arr.size() - 1;
while (lo < hi) {
// Increment lo index while we see 0 at lo
while (arr[lo] == 0 && lo < hi)
lo++;
// Decrement hi index while we see 1 at hi
while (arr[hi] == 1 && lo < hi)
hi--;
// If lo is smaller than hi, then there is
// a 1 at lo and a 0 at hi
if (lo < hi) {
swap(arr[lo], arr[hi]);
lo++;
hi--;
}
}
}
int main() {
vector<int> arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
cout << "Array after segregation: ";
for (int x : arr)
cout << x << " ";
return 0;
}
#include <stdio.h>
void segregate0and1(int arr[], int n) {
int lo = 0, hi = n - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
int main() {
int arr[] = {0, 1, 0, 1, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
printf("Array after segregation: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
import java.util.Arrays;
public class Segregate0and1 {
public static void segregate0and1(int[] arr) {
int lo = 0, hi = arr.length - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
System.out.print("Array after segregation: ");
System.out.println(Arrays.toString(arr));
}
}
def segregate0and1(arr):
lo, hi = 0, len(arr) - 1
while lo < hi:
while arr[lo] == 0 and lo < hi:
lo += 1
while arr[hi] == 1 and lo < hi:
hi -= 1
if lo < hi:
arr[lo], arr[hi] = arr[hi], arr[lo]
lo += 1
hi -= 1
arr = [0, 1, 0, 1, 1, 1]
segregate0and1(arr)
print("Array after segregation:", arr)
using System;
using System.Linq;
class Program {
static void Segregate0and1(int[] arr) {
int lo = 0, hi = arr.Length - 1;
while (lo < hi) {
while (arr[lo] == 0 && lo < hi) lo++;
while (arr[hi] == 1 && lo < hi) hi--;
if (lo < hi) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
}
}
}
static void Main() {
int[] arr = {0, 1, 0, 1, 1, 1};
Segregate0and1(arr);
Console.WriteLine("Array after segregation: " + string.Join(" ", arr));
}
}
function segregate0and1(arr) {
let lo = 0, hi = arr.length - 1;
while (lo < hi) {
while (arr[lo] === 0 && lo < hi) lo++;
while (arr[hi] === 1 && lo < hi) hi--;
if (lo < hi) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
lo++;
hi--;
}
}
}
let arr = [0, 1, 0, 1, 1, 1];
segregate0and1(arr);
console.log("Array after segregation:", arr);
Output
Array after segregation: 0 0 1 1 1 1
Time Complexity : O(n)
Auxiliary Space: O(1)
The above approach is mainly derived from Hoare’s Partition Algorithm in QuickSort
More Efficient Implementation of the Above Approach
1. Take two pointer lo (for element 0) starting from beginning (index = 0) and hi(for element 1) starting from end (index = array.length-1).
Initialize lo = 0 and hi = array.length-1
2. It is intended to Put 1 to the right side of the array. Once it is done, then 0 will definitely towards the left side of the array.
#include <iostream>
#include <vector>
using namespace std;
// Function to put all 0s on the left and
// all 1s on the right
void segregate0and1(vector<int>& arr) {
int lo = 0;
int hi = arr.size() - 1;
while (lo < hi) {
// If we have a 1 at lo
if (arr[lo] == 1) {
// And a 0 at hi
if (arr[hi] != 1) {
swap(arr[lo], arr[hi]);
lo++;
hi--;
}
else {
hi--;
}
} else {
lo++;
}
}
}
int main() {
vector<int> arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
cout << "Array after segregation is ";
for (int x : arr)
cout << x << " ";
return 0;
}
#include <stdio.h>
void segregate0and1(int arr[], int n) {
int lo = 0;
int hi = n - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
int main() {
int arr[] = {0, 1, 0, 1, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
segregate0and1(arr, n);
printf("Array after segregation is ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
import java.util.Arrays;
public class Segregate0And1 {
public static void segregate0and1(int[] arr) {
int lo = 0;
int hi = arr.length - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 1, 1};
segregate0and1(arr);
System.out.print("Array after segregation is ");
System.out.println(Arrays.toString(arr));
}
}
def segregate0and1(arr):
lo = 0
hi = len(arr) - 1
while lo < hi:
if arr[lo] == 1:
if arr[hi] != 1:
arr[lo], arr[hi] = arr[hi], arr[lo]
lo += 1
hi -= 1
else:
hi -= 1
else:
lo += 1
arr = [0, 1, 0, 1, 1, 1]
segregate0and1(arr)
print("Array after segregation is:", arr)
using System;
class Program {
static void Segregate0and1(int[] arr) {
int lo = 0;
int hi = arr.Length - 1;
while (lo < hi) {
if (arr[lo] == 1) {
if (arr[hi] != 1) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
static void Main() {
int[] arr = {0, 1, 0, 1, 1, 1};
Segregate0and1(arr);
Console.WriteLine("Array after segregation is: " + string.Join(" ", arr));
}
}
function segregate0and1(arr) {
let lo = 0;
let hi = arr.length - 1;
while (lo < hi) {
if (arr[lo] === 1) {
if (arr[hi] !== 1) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
lo++;
hi--;
} else {
hi--;
}
} else {
lo++;
}
}
}
let arr = [0, 1, 0, 1, 1, 1];
segregate0and1(arr);
console.log('Array after segregation is:', arr);
Output
Array after segregation is 0 0 1 1 1 1