Segregate 0s and 1s in an array

Last Updated : 9 Apr, 2026

Given an array arr[] consisting of only 0's and 1's. Modify the array in-place to segregate 0s onto the left side and 1s onto the right side of the array.

Input : arr[] = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

Input : arr[] = [0, 1, 0]
Output : [0, 0, 1]

Input : arr[] = [1, 1]
Output : [1, 1]

Input : arr[] = [0]
Output : [0]

Try It Yourself
redirect icon

[Naive Approach] Count 1s and 0s - Two Traversals - O(n) Time and O(1) Space

  • Traverse the array once to count the number of 0s.
  • Calculate the number of 1s as array length - number of 0s.
  • Update the array by filling the first part with all 0s and the remaining positions with 1s.
C++
#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);
    for (int x : arr)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

// Function to segregate 0s and 1s
class GfG {

    static void segregate0and1(Integer[] arr) {

        // Count 0s
        int count = 0;
        for (int x : arr)
            if (x == 0)
                count++;

        // Fill the array with 0s until count
        for (int i = 0; i < count; i++)
            arr[i] = 0;

        // Fill the remaining array space with 1s
        for (int i = count; i < arr.length; i++)
            arr[i] = 1;
    }

    public static void main(String[] args) {
        Integer[] arr = {0, 1, 0, 1, 1, 1};

        segregate0and1(arr);

        for (int x : arr)
            System.out.print(x + " ");
    }
}
Python
# Function to segregate 0s and 1s
def segregate0and1(arr):

    # Count 0s
    count = 0
    for x in arr:
        if x == 0:
            count += 1

    # Fill the vector with 0s until count
    for i in range(0, count):
        arr[i] = 0

    # Fill the remaining vector space with 1s
    for i in range(count, len(arr)):
        arr[i] = 1


def main():
    arr = [0, 1, 0, 1, 1, 1]

    segregate0and1(arr)
    for x in arr:
        print(x, end=" ")


if __name__ == "__main__":
    main()
C#
using System;

// Function to segregate 0s and 1s
class GfG {

    static void segregate0and1(int[] arr) {

        // Count 0s
        int count = 0;
        foreach (int x in arr)
            if (x == 0)
                count++;

        // Fill the array with 0s until count
        for (int i = 0; i < count; i++)
            arr[i] = 0;

        // Fill the remaining array space with 1s
        for (int i = count; i < arr.Length; i++)
            arr[i] = 1;
    }

    static void Main() {
        int[] arr = { 0, 1, 0, 1, 1, 1 };

        segregate0and1(arr);

        foreach (int x in arr)
            Console.Write(x + " ");
    }
}
JavaScript
// Function to segregate 0s and 1s
function segregate0and1(arr) {

    // Count 0s
    let count = 0;
    for (let x of arr)
        if (x === 0)
            count++;

    // Fill the vector with 0s until count
    for (let i = 0; i < count; i++)
        arr[i] = 0;

    // Fill the remaining vector space with 1s
    for (let i = count; i < arr.length; i++)
        arr[i] = 1;
}

function main() {
    let arr = [0, 1, 0, 1, 1, 1];

    segregate0and1(arr);
    for (let x of arr)
        process.stdout.write(x + " ");
}

main();

Output
0 0 1 1 1 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] Using Hoare's Partition Algorithm - O(n) Time and O(1) Space

  • Use two pointers i and j, where i starts from the beginning (initialized to -1) and j starts from the end (initialized to n).
  • In each iteration, move i forward until you find an element that is not 0, and move j backward until you find an element that is not 1. If i is still less than j, swap the elements at these positions.
  • Repeat this process until i becomes greater than or equal to j. This way, all 0s move to the left side and all 1s move to the right side of the array.
C++
#include <iostream>
#include <vector>
using namespace std;

void segregate0and1(vector<int>& arr) {
  
    int n = arr.size();
    
    // Initialize lo and hi indexes
    int lo = -1, hi = n;

    while (true) {

        // Increment lo index while we see 0 at lo
        do {
            lo++;
        } while (lo < n && arr[lo] == 0);

        // Decrement hi index while we see 1 at hi
        do {
            hi--;
        } while (hi >= 0 && arr[hi] == 1);

        // Break when pointers cross
        if (lo >= hi)
            break;

        // Swap elements
        swap(arr[lo], arr[hi]);
    }
}

int main() {
    vector<int> arr = {0, 1, 0, 1, 1, 1};

    segregate0and1(arr);
    for (int x : arr)
        cout << x << " ";
    return 0;
}
Java
import java.util.*;

class GfG {

    static void segregate0and1(Integer[] arr) {

        int n = arr.length;

        // Initialize lo and hi indexes
        int lo = -1, hi = n;

        while (true) {

            // Increment lo index while we see 0 at lo
            do {
                lo++;
            } while (lo < n && arr[lo] == 0);

            // Decrement hi index while we see 1 at hi
            do {
                hi--;
            } while (hi >= 0 && arr[hi] == 1);

            // Break when pointers cross
            if (lo >= hi)
                break;

            // Swap elements
            int temp = arr[lo];
            arr[lo] = arr[hi];
            arr[hi] = temp;
        }
    }

    public static void main(String[] args) {
        Integer[] arr = {0, 1, 0, 1, 1, 1};

        segregate0and1(arr);
        for (int x : arr)
            System.out.print(x + " ");
    }
}
Python
def segregate0and1(arr):

    n = len(arr)

    # Initialize lo and hi indexes
    lo = -1
    hi = n

    while True:

        # Increment lo index while we see 0 at lo
        while True:
            lo += 1
            if not (lo < n and arr[lo] == 0):
                break

        # Decrement hi index while we see 1 at hi
        while True:
            hi -= 1
            if not (hi >= 0 and arr[hi] == 1):
                break

        # Break when pointers cross
        if lo >= hi:
            break

        # Swap elements
        arr[lo], arr[hi] = arr[hi], arr[lo]


def main():
    arr = [0, 1, 0, 1, 1, 1]

    segregate0and1(arr)
    for x in arr:
        print(x, end=" ")


if __name__ == "__main__":
    main()
C#
using System;

class GfG {

    static void segregate0and1(int[] arr) {

        int n = arr.Length;

        // Initialize lo and hi indexes
        int lo = -1, hi = n;

        while (true) {

            // Increment lo index while we see 0 at lo
            do {
                lo++;
            } while (lo < n && arr[lo] == 0);

            // Decrement hi index while we see 1 at hi
            do {
                hi--;
            } while (hi >= 0 && arr[hi] == 1);

            // Break when pointers cross
            if (lo >= hi)
                break;

            // Swap elements
            int temp = arr[lo];
            arr[lo] = arr[hi];
            arr[hi] = temp;
        }
    }

    static void Main() {
        int[] arr = { 0, 1, 0, 1, 1, 1 };

        segregate0and1(arr);

        foreach (int x in arr)
            Console.Write(x + " ");
    }
}
JavaScript
function segregate0and1(arr) {

    let n = arr.length;

    // Initialize lo and hi indexes
    let lo = -1, hi = n;

    while (true) {

        // Increment lo index while we see 0 at lo
        do {
            lo++;
        } while (lo < n && arr[lo] === 0);

        // Decrement hi index while we see 1 at hi
        do {
            hi--;
        } while (hi >= 0 && arr[hi] === 1);

        // Break when pointers cross
        if (lo >= hi)
            break;

        // Swap elements
        let temp = arr[lo];
        arr[lo] = arr[hi];
        arr[hi] = temp;
    }
}

function main() {
    let arr = [0, 1, 0, 1, 1, 1];

    segregate0and1(arr);
    for (let x of arr)
        process.stdout.write(x + " ");
}

main();

Output
0 0 1 1 1 1 
Comment