Sunday, November 17, 2024
Google search engine
HomeLanguagesPython3 Program for Segregate 0s and 1s in an array

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

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) 

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.


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.

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):
            (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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000neveropen! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments