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