Python Program for 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. Traverse array only once.
Example:
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: Using sort() function
Python3
arr = [ 0 , 1 , 0 , 1 , 1 , 1 ]
arr.sort()
print ( "Array after segregation is" , end = ' ' )
print ( * arr)
|
Output
Array after segregation is 0 0 1 1 1 1
Time Complexity: O(n*logn)
Auxiliary Space: O(1)
Method 2: (Count 0s or 1s)
- Count the number of 0s. Let count be C.
- 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)
Auxiliary Space: O(1)
Thanks to Naveen for suggesting this method.
Method 3: (Use two indexes to traverse)
Method 2 traverses the array two times. Method 3 does the same in a single pass.
Maintain two indexes. Initialize first index left as 0 and second index right as n-1.
Do the 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:
Python
def segregate0and1(arr, size):
left, right = 0 , size - 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
return arr
arr = [ 0 , 1 , 0 , 1 , 1 , 1 ]
arr_size = len (arr)
print ( "Array after segregation" )
print (segregate0and1(arr, arr_size))
|
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 left side of array.
Please refer complete article on Segregate 0s and 1s in an array for more details!
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...