We 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 : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : arr = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Input : arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1] Output : arr = [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
We have already discussed a solution Segregate 0s and 1s in an array
In this post, a new solution is discussed.
Step 1 : Here we can take two pointers type0 (for element 0) starting from beginning (index = 0) and type1 (for element 1) starting from end index.
Step 2: We intend to put 1 to the right side of the array. Once we have done this then 0 will definitely towards left side of array to achieve this we do following.
We compare elements at index type0
1) if this is 1 then this should be moved to right side so we need to swap this with index type1 once swapped we are sure that element at index type1 is ‘1’ so we need to decrement index type1
2) else it will be 0 then we need to simple increment index type0
Time Complexity : O(n)
0 0 0 1 1 1 1 1 1 1 1
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find Kth element in an array containing odd elements first and then even elements
- Split an array containing N elements into K sets of distinct elements
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Sort Linked List containing values from 1 to N
- Add elements in start to sort the array | Variation of Stalin Sort
- Find four missing numbers in an array containing elements from 1 to N
- Insertion sort to sort even and odd positioned elements in different orders
- Find smallest range containing elements from k lists
- Count of subsets not containing adjacent elements
- Number of subsequences of maximum length K containing no repeated elements
- Minimum length subarray containing all unique elements after Q operations
- Count of subsequences of length atmost K containing distinct prime elements
- Sort an almost sorted array where only two elements are swapped
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Bucket Sort To Sort an Array with Negative Numbers
- Program to sort an array of strings using Selection Sort
- Sort an Array which contain 1 to N values in O(N) using Cycle Sort
- Longest sub-sequence of array containing Lucas numbers
- Check if product of array containing prime numbers is a perfect square
- Count of Subarrays in an array containing numbers from 1 to the length of subarray
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.