Sorting a Linked List of 0's, 1's and 2's
Problem Statement:-
Given a linked list of N nodes where nodes can contain values 0s, 1s, and 2s only. The task is to segregate 0s, 1s, and 2s linked list such that all zeros segregate to the head side, 2s at the end of the linked list, and 1s in the mid of 0s and 2s.
Example 1:
Input:
N = 8
value[] = {1,2,2,1,2,0,2,2}
Output: 0 1 1 2 2 2 2 2
Explanation: All the 0s are segregated
to the left end of the linked list,
2s to the right end of the list, and
1s in between.
Link to Problem: Sorting a Linked List of 0's, 1's and 2's
Solution:-
The basic approach to solve this problem would be to store the count of 0's, 1's, and 2's and then changing the value of the nodes of the LinkedList.
And this is an optimal approach as well, many people will argue that since we are storing the count of 0's, 1's, and 2's, it will be using O(N) extra space. But no, we will be using O(1) space to store the count of elements, since, for each test case, we will only require to store the count of 3 numbers (0, 1, 2).
Let us now look at the solution:
Node* segregate(Node *head) {
// first we will be checking if the linked list passed is
// valid or not
if(!head){
return head;
}
Node *ptr = head;
// to store the count of 0, 1 and 2
int count[3] = {0, 0, 0};
while(ptr){
++count[ptr->data];
ptr=ptr->next;
}
ptr = head;
int i = 0;
// updating the value of each node
while(ptr){
if(count[i]==0){
++i;
}else{
ptr->data = i;
ptr = ptr->next;
--count[i];
}
}
return head;
}
Let us now analyze our solution:
The space complexity for this solution would be O(1) since we are not using any extra space for this. The space used will be constant.
The time complexity for this solution would be O(N), where N is the number of nodes in the linked list. We will be traversing the entire linked list to store the count of 0's, 1's, and 2's and then we will again traverse the entire linked list to update the value of each node in ascending order.
You may also refer to my Github Repo where I keep uploading solutions for multiple DSA problems daily.
Comments
Post a Comment