Sort a Linked List of 0s and 1s
Input: head = 1 -> 0 -> 1 -> 0 -> 1 -> 0 -> NULL
Output: 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> NULL
Input: head = 1 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 1 -> NULL
Naive Approach: The simplest approach to solve the given problem is to perform the merge sort or insertion sort on the given linked list and sort it. The Implementation of Sorting the Linked list using Merge sort and Sorting the linked list using Insertion sort is discussed already.
Time complexity: O(N * log N)
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by counting the number of 1s and 0s in the given linked list and update the value of nodes accordingly in the linked list. Follow the steps to solve the problem:
- Traverse the given linked list and store the count of 0s and 1s in variables, say zeroes and ones respectively.
- Now, traverse the linked list again and change the first zeroes nodes with value 0 and then the remaining nodes with the value 1.
- After completing the above steps, print the linked list as the resultant sorted list.
Below is the implementation of the above approach:
0 0 0 1 1 1 1 1 1
Time Complexity: O(N)
Auxiliary Space: O(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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.