## Brute Force approach - (Count 0s or 1s)

In this method we will first count the number of 0s and 1s and fill the array accordingly.

### Steps of Algorithm

- Suppose the array is {0,1,0,1, 0}. The size of the array is 4. We will first count the number of 0s which in this case is 2. Now we can get the number of 1s by subtracting the number of 0s from the size. (5-3=2)
- Once we have counted the 0s and 1s, we can fill the array. First we will fill the zeros and then ones (we can get number of ones by using the above formula).

### Implementation

- C++
- Java
- Python
- Javascript
- C#

### C++

`#include <bits/stdc++.h>`

using namespace std;

void segregating0sand1s(int arr[], int n)

{

int count = 0;

for (int i = 0; i < n; i++) {

if (arr[i] == 0) // to counts the no of zeros in arr

count++;

}

for (int i = 0; i < count; i++)

arr[i] = 0; // loop to fill the arr with 0 until count

for (int i = count; i < n; i++)

arr[i] = 1; // loop to fill remaining arr space with 1

}

void print(int arr[], int n)

{

cout << "Array after segregating 0s and 1s is ";

for (int i = 0; i < n; i++)

cout << arr[i] << " ";

}

// Driver function

int main()

{

int arr[] = { 1, 1, 0, 1, 0, 1 };

int n = sizeof(arr) / sizeof(arr[0]);

segregating0sand1s(arr, n);

print(arr, n);

return 0;

}

### Java

`public class SegregateZerosOnes {`

static void segregating0sand1s(int[] arr, int n) {

int count = 0;

for (int i = 0; i < n; i++) {

if (arr[i] == 0)

count++;

}

for (int i = 0; i < count; i++)

arr[i] = 0;

for (int i = count; i < n; i++)

arr[i] = 1;

}

static void print(int[] arr, int n) {

System.out.print("Array after segregating 0s and 1s is ");

for (int i = 0; i < n; i++)

System.out.print(arr[i] + " ");

}

public static void main(String[] args) {

int[] arr = {1, 1, 0, 1, 0, 1};

int n = arr.length;

segregating0sand1s(arr, n);

print(arr, n);

}

}

### Python

`def segregating0sand1s(arr):`

count = arr.count(0)

arr[:count] = [0] * count

arr[count:] = [1] * (len(arr) - count)

def print_array(arr):

print("Array after segregating 0s and 1s is", end=" ")

for num in arr:

print(num, end=" ")

arr = [1, 1, 0, 1, 0, 1]

segregating0sand1s(arr)

print_array(arr)

### Javascript

`function segregating0sand1s(arr) {`

const count = arr.filter(num => num === 0).length;

arr.fill(0, 0, count);

arr.fill(1, count);

}

function printArray(arr) {

process.stdout.write("Array after segregating 0s and 1s is ");

for (let i = 0; i < arr.length; i++) {

process.stdout.write(arr[i] + " ");

}

}

const arr = [1, 1, 0, 1, 0, 1];

segregating0sand1s(arr);

printArray(arr);

### C#

`using System;`

class SegregateZerosOnes {

static void Segregating0sand1s(int[] arr) {

int count = 0;

foreach (int num in arr) {

if (num == 0)

count++;

}

for (int i = 0; i < count; i++)

arr[i] = 0;

for (int i = count; i < arr.Length; i++)

arr[i] = 1;

}

static void Print(int[] arr) {

Console.Write("Array after segregating 0s and 1s is ");

foreach (int num in arr) {

Console.Write(num + " ");

}

}

static void Main(string[] args) {

int[] arr = {1, 1, 0, 1, 0, 1};

Segregating0sand1s(arr);

Print(arr);

}

}

**Output:**

`Array after segregating 0s and 1s is 0 0 1 1 1 1.`

### Complexity Analysis

The time complexity is **O(n)**.

The space complexity is **O(1)**.

The above approach traverses the array two times. Below we will talk of a more optimized solution which traverses array single time.

## Optimized Approach - (Use two indexes to traverse)

This approach traverses the array only once. Here we maintain two indexes where the left index is initialized as 0 and the right index as n-1. We then check the conditions and move the pointers accordingly.

### Steps of Algorithm

while (left < right)

- Keep incrementing index left if it is equal to 0s
- Keep decrementing index right if it is equal to 1s
- If left < right then we will exchange arr[left] and arr[right]

### Implementation

- C++
- Java
- Python
- Javascript
- C#

### C++

`#include <bits/stdc++.h>`

using namespace std;

void segregating0sand1s(int arr[], int size)

{

int left = 0, right = size-1;

while (left < right)

{

while (arr[left] == 0 && left < right)

left++;

while (arr[right] == 1 && left < right)

right--;

if (left < right)

{

arr[left] = 0;

arr[right] = 1;

left++;

right--;

}

}

}

/* Driver code */

int main()

{

int arr[] = {1, 1, 0, 1, 1, 0};

int i, arr_size = sizeof(arr)/sizeof(arr[0]);

segregating0sand1s(arr, arr_size);

cout << "Array after segregating 0s and 1s is ";

for (i = 0; i < 6; i++)

cout << arr[i] << " ";

return 0;

}

### Java

`public class SegregateZerosOnes {`

static void segregating0sand1s(int[] arr) {

int left = 0, right = arr.length - 1;

while (left < right) {

while (arr[left] == 0 && left < right)

left++;

while (arr[right] == 1 && left < right)

right--;

if (left < right) {

arr[left] = 0;

arr[right] = 1;

left++;

right--;

}

}

}

public static void main(String[] args) {

int[] arr = {1, 1, 0, 1, 1, 0};

segregating0sand1s(arr);

System.out.print("Array after segregating 0s and 1s is ");

for (int i = 0; i < arr.length; i++)

System.out.print(arr[i] + " ");

}

}

### Python

`def segregating0sand1s(arr):`

left, right = 0, len(arr) - 1

while left < right:

while arr[left] == 0 and left < right:

left += 1

while arr[right] == 1 and left < right:

right -= 1

if left < right:

arr[left] = 0

arr[right] = 1

left += 1

right -= 1

arr = [1, 1, 0, 1, 1, 0]

segregating0sand1s(arr)

print("Array after segregating 0s and 1s is", end=" ")

print(*arr)

### Javascript

`function segregating0sand1s(arr) {`

let left = 0, right = arr.length - 1;

while (left < right) {

while (arr[left] === 0 && left < right)

left++;

while (arr[right] === 1 && left < right)

right--;

if (left < right) {

arr[left] = 0;

arr[right] = 1;

left++;

right--;

}

}

}

const arr = [1, 1, 0, 1, 1, 0];

segregating0sand1s(arr);

process.stdout.write("Array after segregating 0s and 1s is ");

console.log(arr.join(" "));

### C#

`using System;`

class SegregateZerosOnes {

static void Segregating0sand1s(int[] arr) {

int left = 0, right = arr.Length - 1;

while (left < right) {

while (arr[left] == 0 && left < right)

left++;

while (arr[right] == 1 && left < right)

right--;

if (left < right) {

arr[left] = 0;

arr[right] = 1;

left++;

right--;

}

}

}

static void Main(string[] args) {

int[] arr = {1, 1, 0, 1, 1, 0};

Segregating0sand1s(arr);

Console.Write("Array after segregating 0s and 1s is ");

foreach (int num in arr) {

Console.Write(num + " ");

}

}

}

**Output:**

`Array after segregating 0s and 1s is 0 0 1 1 1 1.`

### Complexity Analysis

The time complexity is **O(n)**.

The space complexity is **O(1)**.

## Frequently Asked Questions

**How to segregate 0 and 1 in an array in Java?**

To segregate 0s and 1s in Java, iterate through the array, moving 0s to the beginning and 1s to the end.

**How to separate 0 and 1 in an array in Python?**

To separate 0s and 1s in Python, use two pointers, one from the start and one from the end, swapping 0s and 1s until pointers meet.

**How do you segregate an array?**

To segregate an array, iterate through it, moving specific elements based on a condition, such as separating 0s and 1s.

**What is the sequence of 0s and 1s?**

The sequence of 0s and 1s in an array depends on the segregation process applied, where either 0s precede 1s or vice versa.

## Conclusion

This article discussed the solution for segregating 0s and 1s in an array along with its different approaches, pseudocode, implementation, and code in both JAVA and C++.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in __Data Structures and Algorithms__, __Competitive Programming__, __JavaScript__, __System Design__, __Machine learning__ and many more! If you want to test your competency in coding, you may check out the mock __test series__ and participate in the __contests__ hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the__ problems__, __interview experiences__, and __interview bundle__ for placement preparations.

Nevertheless, you may consider our paid __courses__ to give your career an edge over others!

Recommended Problems -

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!