Python3 Program for Segregate 0s and 1s in an array
Last Updated :
05 Sep, 2024
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. 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]
Method 1 (Count 0s or 1s)
Thanks to Naveen for suggesting this method.
1) Count the number of 0s. Let count be C.
2) Once we have count, we can put C 0s at the beginning and 1s at the remaining n - C positions in array.
Time Complexity : O(n)
Python
# 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.
Output :
Array after segregation is 0 0 1 1 1 1
Time Complexity : O(n) as it is looping through the array three times, which is linear time complexity.Here, n is size of input array.
Space Complexity: O(1) as it is not using any extra space other than the given array.
The method 1 traverses the array two times. Method 2 does the same in a single pass.
Method 2 (Use two indexes to traverse)
Maintain two indexes. Initialize 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:
Output:
Array after segregation is 0 0 1 1 1 1
Time Complexity: O(n)
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 left side of array.
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):
type0 = 0
type1 = size - 1
while(type0 < type1):
if(arr[type0] == 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
Output:
Array after segregation is 0 0 1 1 1 1
Time complexity: O(n)
Please refer complete article on Segregate 0s and 1s in an array for more details!
Similar Reads
Python Program to Sort an array of 0s, 1s and 2s Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last. Examples: Input : {0, 1, 2, 0, 1, 2, 2, 2, 2, 1} Output : {0, 0, 1, 1, 1, 2, 2, 2, 2, 2} Input : {0, 1, 1, 0, 1, 2, 1, 2, 0,
2 min read
Segregate 0's and 1's in an array list - Python Segregating 0s and 1s in an array involves rearranging the elements so that all 0s appear before 1s. This can be done using different methods, such as list comprehension, sort() method or a two-pointer approach, each offering varying levels of efficiency and simplicityUsing List ComprehensionTo segr
3 min read
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
13 min read
Array in Python | Set 1 (Introduction and Functions) Other than some generic containers like lists, Python in its definition can also handle containers with specified data types. The array can be handled in Python by a module named "array". They can be useful when we have to manipulate only specific data type values. Properties of ArraysEach array ele
7 min read
Check if a given string is binary string or not - Python The task of checking whether a given string is a binary string in Python involves verifying that the string contains only the characters '0' and '1'. A binary string is one that is composed solely of these two digits and no other characters are allowed. For example, the string "101010" is a valid bi
3 min read
Create a Numpy array filled with all zeros - Python In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array. We can use Numpy.zeros() method to do this task. Let's understand with the help of an example:Pythonimport numpy as np # Create a 1D array of zeros with 5 elements array_1d = np.zeros
2 min read