23. Given a linked list of 0s, 1s and 2s, sort it.
My Approach
Time and Auxiliary Space Complexity
Code (C++)
class Solution
{
public:
Node* segregate(Node* head)
{
vector<int> cnt(3, 0);
Node* itr = head;
// Count occurrences of 0s, 1s, and 2s
while (itr)
{
++cnt[itr->data];
itr = itr->next;
}
int i = 0;
itr = head;
// Replace node data based on counts
while (itr)
{
int c = 0;
while (c < cnt[i])
{
itr->data = i;
itr = itr->next;
++c;
}
++i;
}
return head;
}
};Contribution and Support
Last updated