The Wayback Machine - https://web.archive.org/web/20241001040932/https://www.geeksforgeeks.org/segregate-0s-and-1s-in-an-array-by-traversing-array-once/
Open In App

Segregate 0s and 1s in an array

Last Updated : 22 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 array   =  [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output array =  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 
Recommended Practice

Method 1 (Count 0s or 1s) 
Thanks to Naveen for suggesting this method. 
1) Count the number of 0s. So 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.

2) 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).

C++




// C++ code to Segregate 0s and 1s in an array
#include <bits/stdc++.h>
using namespace std;
  
// 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)
{
    cout << "Array after segregation is ";
  
    for (int i = 0; i < n; i++)
        cout << 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)


C




// 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




// 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


Python3




# 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#




// 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.


PHP




<?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
?>


Javascript




<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>


Output

Array after segregation is 0 0 1 1 1 1 

Time Complexity : O(2n)  ≅ O(n)
Auxiliary Space: O(1)

Method 1 traverses the array two times. Method 2 does the same in a single pass.

Method 1 has time complexity of O(2n) and Method 2 has time complexity of O(n)

Method 2 (Use two indexes to traverse) 
Maintain two indexes. Initialize the first index left as 0 and second index right as n-1.
Do following while left < right 
a) Keep incrementing index left while there are 0s at it 
b) Keep decrementing index right while there are 1s at it 
c) If left < right then exchange arr[left] and arr[right]

Implementation: 

C++




// C++ program to sort a binary array in one pass 
#include <bits/stdc++.h>
using namespace std;
  
/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size) 
{ 
    /* Initialize left and right indexes */
    int left = 0, right = size-1; 
  
    while (left < right) 
    { 
        /* Increment left index while we see 0 at left */
        while (arr[left] == 0 && left < right) 
            left++; 
  
        /* Decrement right index while we see 1 at right */
        while (arr[right] == 1 && left < right) 
            right--; 
  
        /* If left is smaller than right then there is a 1 at left 
        and a 0 at right. Exchange arr[left] and arr[right]*/
        if (left < right) 
        { 
            arr[left] = 0; 
            arr[right] = 1; 
            left++; 
            right--; 
        } 
    } 
} 
  
/* Driver code */
int main() 
{ 
    int arr[] = {0, 1, 0, 1, 1, 1}; 
    int i, arr_size = sizeof(arr)/sizeof(arr[0]); 
  
    segregate0and1(arr, arr_size); 
  
    cout << "Array after segregation "; 
    for (i = 0; i < 6; i++) 
        cout << arr[i] << " "; 
    return 0; 
} 
  
// This is code is contributed by rathbhupendra


C




// C program to sort a binary array in one pass
#include<stdio.h>
  
/*Function to put all 0s on left and all 1s on right*/
void segregate0and1(int arr[], int size)
{
    /* Initialize left and right indexes */
    int left = 0, right = size-1;
  
    while (left < right)
    {
        /* Increment left index while we see 0 at left */
        while (arr[left] == 0 && left < right)
            left++;
  
        /* Decrement right index while we see 1 at right */
        while (arr[right] == 1 && left < right)
            right--;
  
        /* If left is smaller than right then there is a 1 at left
          and a 0 at right.  Exchange arr[left] and arr[right]*/
        if (left < right)
        {
            arr[left] = 0;
            arr[right] = 1;
            left++;
            right--;
        }
    }
}
  
/* driver program to test */
int main()
{
    int arr[] = {0, 1, 0, 1, 1, 1};
    int i, arr_size = sizeof(arr)/sizeof(arr[0]);
  
    segregate0and1(arr, arr_size);
  
    printf("Array after segregation ");
    for (i = 0; i < 6; i++)
        printf("%d ", arr[i]);
  
    getchar();
    return 0;
}


Java




import java.io.*;
public class Segregate 
{
    /*Function to put all 0s on left and all 1s on right*/
    void segregate0and1(int arr[], int size) 
    {
        /* Initialize left and right indexes */
        int left = 0, right = size - 1;
  
        while (left < right) 
        {
            /* Increment left index while we see 0 at left */
            while (arr[left] == 0 && left < right)
               left++;
  
            /* Decrement right index while we see 1 at right */
            while (arr[right] == 1 && left < right)
                right--;
  
            /* If left is smaller than right then there is a 1 at left
               and a 0 at right.  Exchange arr[left] and arr[right]*/
            if (left < right) 
            {
                arr[left] = 0;
                arr[right] = 1;
                left++;
                right--;
            }
        }
    }
      
    /* Driver Program to test above functions */
    public static void main(String[] args) 
    {
        Segregate seg = new Segregate();
        int arr[] = new int[]{0, 1, 0, 1, 1, 1};
        int i, arr_size = arr.length;
  
        seg.segregate0and1(arr, arr_size);
  
        System.out.print("Array after segregation is ");
        for (i = 0; i < 6; i++)
            System.out.print(arr[i] + " ");
    }
}


Python




# Python program to sort a binary array in one pass
  
# Function to put all 0s on left and all 1s on right
def segregate0and1(arr, size):
    # Initialize left and right indexes
    left, right = 0, size-1
      
    while left < right:
        # Increment left index while we see 0 at left
        while arr[left] == 0 and left < right:
            left += 1
  
        # Decrement right index while we see 1 at right
        while arr[right] == 1 and left < right:
            right -= 1
  
        # If left is smaller than right then there is a 1 at left
        # and a 0 at right. Exchange arr[left] and arr[right]
        if left < right:
            arr[left] = 0
            arr[right] = 1
            left += 1
            right -= 1
  
    return arr
  
# driver program to test
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
print("Array after segregation")
print(segregate0and1(arr, arr_size))
  
# This code is contributed by Pratik Chhajer


C#




// C# program to sort a binary array in one pass
using System;
  
class Segregate 
{
    /*Function to put all 0s on
      left and all 1s on right*/
    void segregate0and1(int []arr, int size) 
    {
        /* Initialize left and right indexes */
        int left = 0, right = size - 1;
  
        while (left < right) 
        {
            /* Increment left index while
               we see 0 at left */
            while (arr[left] == 0 && left < right)
            left++;
  
            /* Decrement right index while 
               we see 1 at right */
            while (arr[right] == 1 && left < right)
                right--;
  
            /* If left is smaller than right then
               there is a 1 at left and a 0 at right. 
               Exchange arr[left] and arr[right]*/
            if (left < right) 
            {
                arr[left] = 0;
                arr[right] = 1;
                left++;
                right--;
            }
        }
    }
      
    /* Driver Program to test above functions */
    public static void Main() 
    {
        Segregate seg = new Segregate();
        int []arr = new int[]{0, 1, 0, 1, 1, 1};
        int i, arr_size = arr.Length;
  
        seg.segregate0and1(arr, arr_size);
  
        Console.WriteLine("Array after segregation is ");
        for (i = 0; i < 6; i++)
            Console.Write(arr[i] + " ");
    }
}
  
//This code is contributed by vt_m.


PHP




<?php
// PHP program to sort a
// binary array in one pass
  
// Function to put all 0s on
// left and all 1s on right
function segregate0and1(&$arr, $size)
{
    // Initialize left and
    // right indexes 
    $left = 0;
    $right = $size - 1;
  
    while ($left < $right)
    {
        // Increment left index 
        // while we see 0 at left 
        while ($arr[$left] == 0 && 
               $left < $right)
            $left++;
  
        // Decrement right index 
        // while we see 1 at right 
        while ($arr[$right] == 1 && 
               $left < $right)
            $right--;
  
        // If left is smaller than right 
        // then there is a 1 at left
        // and a 0 at right. Exchange 
        // arr[left] and arr[right]
        if ($left < $right)
        {
            $arr[$left] = 0;
            $arr[$right] = 1;
            $left++;
            $right--;
        }
    }
}
  
// Driver code
$arr = array(0, 1, 0, 1, 1, 1);
$arr_size = sizeof($arr);
  
segregate0and1($arr, $arr_size);
  
printf("Array after segregation is ");
for ($i = 0; $i < 6; $i++)
    echo ($arr[$i]. " ");
  
// This code is contributed 
// by Shivi_Aggarwal
?>


Javascript




<script>
  
// Javascript program to sort a binary array in one pass
  
/*Function to put all 0s on left and all 1s on right*/
function segregate0and1(arr, size) 
{ 
    /* Initialize left and right indexes */
    let left = 0, right = size-1; 
  
    while (left < right) 
    { 
        /* Increment left index while we see 0 at left */
        while (arr[left] == 0 && left < right) 
            left++; 
  
        /* Decrement right index while we see 1 at right */
        while (arr[right] == 1 && left < right) 
            right--; 
  
        /* If left is smaller than right then there is a 1 at left 
        and a 0 at right. Exchange arr[left] and arr[right]*/
        if (left < right) 
        { 
            arr[left] = 0; 
            arr[right] = 1; 
            left++; 
            right--; 
        } 
    } 
} 
  
/* Driver code */
let arr = [0, 1, 0, 1, 1, 1]; 
let i, arr_size = arr.length; 
  
segregate0and1(arr, arr_size); 
  
document.write("Array after segregation "); 
for (i = 0; i < 6; i++) 
    document.write(arr[i] + " "); 
  
</script>


Output

Array after segregation 0 0 1 1 1 1 

Time Complexity : O(n) 
Auxiliary Space: O(1)

Another approach : 
1. Take two pointer type0(for element 0) starting from beginning (index = 0) and type1(for element 1) starting from end (index = array.length-1). 
Initialize type0 = 0 and type1 = 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.

C++




// C++ program to sort a binary array in one pass
#include <bits/stdc++.h>
using namespace std;
  
// Function to put all 0s on left and all 1s on right
void segregate0and1(int arr[], int size)
{
    int type0 = 0;
    int type1 = size - 1;
  
    while (type0 < type1) {
        if (arr[type0] == 1) {
            if (arr[type1] != 1)
                swap(arr[type0], arr[type1]);
            type1--;
        }
        else
            type0++;
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 0, 1, 0, 1, 1, 1 };
    int i, arr_size = sizeof(arr) / sizeof(arr[0]);
  
    segregate0and1(arr, arr_size);
  
    cout << "Array after segregation is ";
    for (i = 0; i < arr_size; i++)
        cout << arr[i] << " ";
  
    return 0;
}


C




// C program to sort a binary array in one pass
#include <stdio.h>
  
// Function to put all 0s on left and all 1s on right
void segregate0and1(int arr[], int size)
{
    int type0 = 0;
    int type1 = size - 1;
  
    while (type0 < type1) {
        if (arr[type0] == 1) {
            if (arr[type1] != 1) {
                int temp = arr[type0];
                arr[type0] = arr[type1];
                arr[type1] = temp;
            }
            type1--;
        }
        else
            type0++;
    }
}
  
// Driver Code
int main()
{
    int arr[] = { 0, 1, 0, 1, 1, 1 };
    int i, arr_size = sizeof(arr) / sizeof(arr[0]);
  
    segregate0and1(arr, arr_size);
  
    printf("Array after segregation is ");
    for (i = 0; i < arr_size; i++)
        printf("%d ", arr[i]);
  
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java code to segregate 0 and 1
import java.io.*;
import java.util.*;
  
class GFG {
    /**
    Method for segregation 0 and 1 given input array
    */
    static void segregate0and1(int arr[])
    {
        int type0 = 0;
        int type1 = arr.length - 1;
  
        while (type0 < type1) {
            if (arr[type0] == 1) {
                if (arr[type1] != 1) {
                    // swap
                    arr[type1] = arr[type1] + arr[type0];
                    arr[type0] = arr[type1] - arr[type0];
                    arr[type1] = arr[type1] - arr[type0];
                }
                type1--;
            }
            else {
                type0++;
            }
        }
    }
  
    // Driver program
    public static void main(String[] args)
    {
  
        int[] array = { 0, 1, 0, 1, 1, 1 };
  
        segregate0and1(array);
  
        for (int a : array) {
            System.out.print(a + " ");
        }
    }
}


Python3




# Python program to sort a
# binary array in one pass
  
# Function to put all 0s on
# left and all 1s on right
  
  
def segregate0and1(arr, size):
  
    type0 = 0
    type1 = size - 1
  
    while(type0 < type1):
        if(arr[type0] == 1):
            if(arr[type1] != 1):
              (arr[type0],
               arr[type1]) = (arr[type1],
                              arr[type0])
            type1 -= 1
        else:
            type0 += 1
      
# Driver Code
arr = [0, 1, 0, 1, 1, 1]
arr_size = len(arr)
segregate0and1(arr, arr_size)
print("Array after segregation is", 
                         end = " ")
for i in range(0, arr_size):
        print(arr[i], end = " ")
  
# This code is contributed
# by Shivi_Aggarwal


C#




// C# code to segregate 0 and 1
using System;
  
class GFG {
  
    // Method for segregation 0
    // and 1 given input array
    static void segregate0and1(int[] arr)
    {
        int type0 = 0;
        int type1 = arr.Length - 1;
  
        while (type0 < type1) {
            if (arr[type0] == 1) {
                if (arr[type1] != 1) {
                    // swap
                    arr[type1] = arr[type1] + arr[type0];
                    arr[type0] = arr[type1] - arr[type0];
                    arr[type1] = arr[type1] - arr[type0];
                }
                type1--;
            }
  
            else {
                type0++;
            }
        }
    }
  
    // Driver Code
    public static void Main(string[] args)
    {
  
        int[] array = new int[] { 0, 1, 0, 1, 1, 1 };
        segregate0and1(array);
  
        Console.Write("Array after segregation is ");
        foreach(int a in array) { Console.Write(a + " "); }
    }
}
  
// This code is contributed by Shrikant13


PHP




<?php
// PHP program to sort a 
// binary array in one pass
  
// Function to put all 0s on 
// left and all 1s on right
function segregate0and1(&$arr , $size)
{
    $type0 = 0;
    $type1 = $size - 1;
      
    while($type0 < $type1)
    {
        if($arr[$type0] == 1)
        {
              if($arr[$type1] != 1)
            {
              $temp = $arr[$type0];
              $arr[$type0] = $arr[$type1];
              $arr[$type1] = $temp;
            }
            $type1--;
        }
        else
        $type0++;
    }
}
  
// Driver Code
$arr = array(0, 1, 0, 1, 1, 1);
$arr_size = sizeof($arr);
  
segregate0and1($arr, $arr_size);
  
echo ("Array after segregation is ");
for ($i = 0; $i < $arr_size; $i++)
    echo ($arr[$i] . " ");
  
// This code is contributed 
// by Shivi_Aggarwal
?>


Javascript




<script>
  
// Javascript program to sort a 
// binary array in one pass
  
// Function to put all 0s on 
// left and all 1s on right
function segregate0and1(arr, size)
{
    let type0 = 0;
    let type1 = size - 1;
      
    while (type0 < type1)
    {
        if (arr[type0] == 1)
        {
             if (arr[type1] != 1)
            {   
              // Swap
              arr[type1] = arr[type1] + arr[type0];
              arr[type0] = arr[type1] - arr[type0];
              arr[type1] = arr[type1] - arr[type0];
             }
            type1--;
        }
        else
            type0++;
    }
}
  
// Driver Code
let arr = [ 0, 1, 0, 1, 1, 1 ];
let i, arr_size = arr.length;
  
segregate0and1(arr, arr_size);
  
document.write("Array after segregation is ");
for(i = 0; i < arr_size; i++)
    document.write(arr[i] + " ");
      
// This code is contributed by subhammahato348
  
</script>


Output

Array after segregation is 0 0 1 1 1 1 

Time complexity: O(n)
Auxiliary Space: O(1)
// Thanks san4net for suggesting this method.
 

Please write comments if you find any of the above algorithms/code incorrect, or a better way to solve the same problem.
 



Similar Reads

Minimum removals to segregate all 0s and 1s such that count of 0s and 1s are equal
Given a binary string S of length N, the task is to find the minimum number of removals to segregate all the 0s and all the 1s such that all the 0s are before all the 1s and their count are also same. Examples: Input: S = 01001101Output: 2Explanation: If you remove the 1 at index 1 and 0 at index 6, then the string becomes 000111. Input: S = "01"Ou
7 min read
Segregate even and odd numbers | Set 2
Given an array of integers, segregate even and odd numbers in the array. All the even numbers should be present first, and then the odd numbers. Examples: Input : 1 9 5 3 2 6 7 11 Output : 6 2 3 5 7 9 11 1 Input : 1 3 2 4 7 6 9 10 Output : 10 2 6 4 7 9 3 1 We have discussed one approach in Segregate Even and Odd numbers. In this post, a different s
5 min read
Segregate even and odd nodes in a Linked List using Deque
Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes ap
10 min read
Segregate Even and Odd numbers | Set 2
Given an array arr[] of size N, the task is to segregate even and odd numbers. Print all even numbers first, and then odd numbers. Examples: Input: arr[] = {8, 22, 65, 70, 33, 60, 2, 34, 43, 21} Output: {8, 22, 70, 60, 2, 34, 65, 33, 43, 21} Input: arr[] = {18, 52, 37, 70, 3, 63, 2, 34} Output: {18, 52, 70, 2, 34, 37, 3, 63} Linear Approach: This p
5 min read
Segregate 1s and 0s in separate halves of a Binary String
Given a binary string str of even length, consisting of equal number of 0s and 1s, the task is to segregate all 1s and 0s into separate halves by repeatedly reversing a substring. Print the minimum count of reversals required. Examples: Input: str = "01011100"Output: 2Explanation: The operations performed are as follows: "01011100" -> "11101000"
5 min read
Minimize moves to segregate even and odd by swapping adjacent elements
Given an array arr[] of size N, the task is to find the minimum moves to segregate even and odd numbers by swapping two adjacent elements at a time. Example: Input: N = 7, arr = {3, 5, 2, 7, 9, 11, 12}Output: 3Explanation: Swap arr[2] and arr[3] to get arr = {3, 5, 7, 2, 9, 11, 12}.Move 2: Swap arr[3] and arr[4] to get arr = {3, 5, 7, 9, 2, 11, 12}
5 min read
Segregate Even and Odd numbers
Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first, and then odd numbers. Example: Input = {12, 34, 45, 9, 8, 90, 3}Output = {12, 34, 8, 90, 45, 9, 3}In the output, the order of numbers can be changed, i.e., in the above example, 34 can come before 12 and 3 can come before 9. R
15+ min read
Segregate even and odd numbers using Lomuto’s Partition Scheme
Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers. Examples: Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}Output: 2 4 6 8 7 9 1 3 5 Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}Output: 2 4 6 10 7 1 9 3 We have discussed two different approaches in b
7 min read
Segregate even and odd nodes in a Linked List
Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers. Examples: Input: 17->15->8->12->10->5->4->1->7->6->NULLOutput: 8->12->10->4->6->17->15->
15+ min read
Segregate groups of first N numbers having GCD equals to 1
Given a number N. The task is to group all the numbers from 1 to N such GCD of all the numbers in each group is 1 as the number of groups must be minimized. Example: Input: N = 3 Output: 1 2 3 Explanation: gcd(1, 2, 3) = 1 Input: N = 6 Output: 1 2 3 4 5 6 Explanation: gcd(1, 2) = 1 gcd(3, 4) = 1 gcd(5, 6) = 1 Approach: As we know, the fact that GCD
6 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
Array obtained by repeatedly reversing array after every insertion from given array
Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array arr1[] as follows:Step 1: Append 1 into the array a
6 min read
Maximize product of array by replacing array elements with its sum or product with element from another array
Given two arrays A[] and B[] consisting of N integers, the task is to update array A[] by assigning every array element A[i] to a single element B[j] and update A[i] to A[i] + B[j] or A[i] * B[j], such that the product of the array A[] is maximized. Note: Every array element in both the arrays can be paired with a single element from the other arra
7 min read
Reduce array to longest sorted array possible by removing either half of given array in each operation
Given an array arr[] of size N (always power of 2), the task is to find the length of the longest sorted array to which the given array can be reduced by removing either half of the array at each operation. Examples: Input: arr[] = { 11, 12, 1, 2, 13, 14, 3, 4 }Output: 2 Explanation: Removal of the first half of arr[] modifies arr[] to {13, 14, 3,
8 min read
Sum of Bitwise OR of each array element of an array with all elements of another array
Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise OR of each element of arr1[] with every element of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 7 8 9Explanation: For arr[0]: Sum = arr1[0]|arr2[0] + arr1[0]|arr2[1] + arr1[0]|arr2[2], Sum = 1|1 + 1|2 + 1|
11 min read
Convert an array into Bitonic array by right shifting array elements
Giver an array arr[] consisting of N integers, the task is to perform right shift operations on array elements to convert the given array into a bitonic array. Examples: Input: arr[] = {7, 3, 4, 5, 3}Output: 56 96 128 80 48Explanation:Perform the operation on the array elements as: 7 ? 00000111 ? 3 right shifts ? 00111000 ? 563 ? 00000011 ? 5 right
11 min read
Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4, 6, 8, 2}, K = 2Output: 44Explanation:The followi
14 min read
Construct array B as last element left of every suffix array obtained by performing given operations on every suffix of given array
Given an array arr[] of N integers, the task is to print the last element left of every suffix array obtained by performing the following operation on every suffix of the array, arr[]: Copy the elements of the suffix array into an array suff[].Update ith suffix element as suff[i] = (suff[i] OR suff[i+1]) - (suff[i] XOR suff[i+1]) reducing the size
9 min read
Modify array by making all array elements equal to 0 by subtracting K^i from an array element in every i-th step
Given an array arr[] of size N, the task is to check if it is possible to convert all array elements to 0s, by subtracting Ki from an array element, in the ith step. If it is possible to do so, then print "Yes". Otherwise, print "No". Examples: Input: N = 5, K = 2, arr[] = {8, 0, 3, 4, 80}Output: YesExplanation: One possible sequence of operations
8 min read
Check whether an array can be fit into another array rearranging the elements in the array
Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array. Examples: Input : A[] = { 7, 5, 3, 2 }, B[]
6 min read
Find original array from encrypted array (An array of sums of other elements)
Find original array from a given encrypted array of size n. Encrypted array is obtained by replacing each element of the original array by the sum of the remaining array elements. Examples : Input : arr[] = {10, 14, 12, 13, 11} Output : {5, 1, 3, 2, 4} Original array {5, 1, 3, 2, 4} Encrypted array is obtained as: = {1+3+2+4, 5+3+2+4, 5+1+2+4, 5+1+
6 min read
Find an element in array such that sum of left array is equal to sum of right array
Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4, 5] Input: 1 2 3Output: -1Explanation: No sub-arr
15+ min read
Maximize sum of array by reducing array elements to contain no triplets (i, j, k) where a[i] < a[j] and a[i] < a[k] and j <i < k
Given an array arr[] consisting of N integers, the task is to find the maximum sum of an array formed by decreasing array elements by 1 any number of times(possibly zero) such that there are no triplets (i, j, k)( 1-based indexing ) such that arr[j] > arr[i] and arr[k] > arr[i], where 1 ? j < i < k ? N. Print the resultant array also af
15+ min read
Minimize swaps required to place largest and smallest array elements at first and last array indices
Given an array arr[] of size N, the task is to find the minimum count of adjacent swaps required to rearrange the array elements such that the largest and the smallest array element present on the first and the last indices of the array respectively. Examples: Input: arr[] = {33, 44, 11, 12} Output: 2 Explanation: Swapping the pair (arr[0], arr[1])
8 min read
Generate an N-length array having length of non-decreasing subarrays maximized and minimum difference between first and last array elements
Given an array arr[ ] of size N, the task is to print an N-length array whose sum of lengths of all non-decreasing subarrays is maximum and the difference between the first and last elements is minimum. Examples: Input: N = 5, arr = {4, 3, 5, 3, 2}Output: {3, 4, 5, 2, 3}Explanation: Difference between the first and last element is minimum, i.e. 3 -
6 min read
Find N-1 pairs (X, Y) from given array such that X and Y are different and X modulo Y is not present in array
Given an array Arr[] of size N consisting of N pairwise distinct positive integers. The task is to find N - 1 different pair of positive integers X, Y that satisfy the following conditions : X ≠ YX, Y both belong to the array.X mod Y does not belong to the array. Note: It is proved that N-1 such pairs always exists. Examples: Input: N = 4 , Arr [ ]
5 min read
Minimum count of array elements that must be changed such that difference between maximum and minimum array element is N - 1
Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be changed to any arbitrary integers such that the difference between maximum and minimum array element is (N - 1) and all array elements must be distinct. Examples: Input: arr[] = {1, 2, 3, 5, 6}Output: 1Explanation:Change 6->4, the
7 min read
Find numbers which are multiples of first array and factors of second array
Given two arrays A[] and B[], the task is to find the integers which are divisible by all the elements of array A[] and divide all the elements of array B[]. Examples: Input: A[] = {1, 2, 2, 4}, B[] = {16, 32, 64} Output: 4 8 16 4, 8 and 16 are the only numbers that are multiples of all the elements of array A[] and divide all the elements of array
7 min read