29. Sort a Linked List of 0s, 1s, and 2s
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given the head of a linked list where each node contains a value of either 0
, 1
, or 2
, your task is to rearrange the list such that all 0
s appear first, followed by all 1
s, and all 2
s appear at the end.
๐ Examples
Example 1:
Input:
head = 1 โ 2 โ 2 โ 1 โ 2 โ 0 โ 2 โ 2
Output:
0 โ 1 โ 1 โ 2 โ 2 โ 2 โ 2 โ 2
Explanation:
After sorting, all the 0
s are at the beginning, followed by the 1
s, and all the 2
s appear at the end of the list.
Example 2:
Input:
head = 2 โ 2 โ 0 โ 1
Output:
0 โ 1 โ 2 โ 2
Explanation:
After sorting, the list is rearranged to have 0
at the beginning, followed by 1
, and all 2
s at the end.
๐ Constraints
$( 1 \leq \text{no. of nodes} \leq 10^6 )$
$( 0 \leq node->data \leq 2 )$
โ
My Approach
Optimized Approach (Dutch National Flag Problem)
The problem can be solved using a modified version of the Dutch National Flag problem, which is known for sorting three distinct elements efficiently.
Algorithm Steps:
Three Pointers Approach:
Initialize three pointers:
low
,mid
, andhigh
.Traverse the list and:
If the current nodeโs value is
0
, move it to the beginning (incrementlow
).If the current nodeโs value is
1
, keep it in the middle (incrementmid
).If the current nodeโs value is
2
, move it to the end (decrementhigh
).
Pointer Movement:
The
low
pointer tracks the end of the 0s section.The
mid
pointer tracks the current node.The
high
pointer tracks the start of the 2s section.
End Condition:
The loop ends when
mid
crosseshigh
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
n
is the number of nodes in the list. We only traverse the list once.Expected Auxiliary Space Complexity: O(1), as we use a constant amount of extra space for the pointers.
๐ง Code (C++)
class Solution {
public:
Node* segregate(Node* head) {
int count[3] = {0};
for (Node* curr = head; curr; curr = curr->next) count[curr->data]++;
Node* curr = head;
for (int i = 0; i < 3; i++)
while (count[i]--) curr->data = i, curr = curr->next;
return head;
}
};
๐งโ๐ป Code (Java)
class Solution {
static Node segregate(Node head) {
int[] count = new int[3];
for (Node curr = head; curr != null; curr = curr.next) count[curr.data]++;
Node curr = head;
for (int i = 0; i < 3; i++)
while (count[i]-- > 0) { curr.data = i; curr = curr.next; }
return head;
}
}
๐ Code (Python)
class Solution:
def segregate(self, head):
count = [0, 0, 0]
curr = head
while curr:
count[curr.data] += 1
curr = curr.next
curr = head
for i in range(3):
while count[i]:
curr.data = i
curr = curr.next
count[i] -= 1
return head
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated