Sort a LL of 0's 1's and 2's

Linked-List Logic Building Medium

Given the head of a singly linked list consisting of only 0, 1 or 2. Sort the given linked list and return the head of the modified list. Do it in-place by changing the links between the nodes without creating new nodes.

Examples:

Input: head -> 1 -> 0 -> 2 -> 0 -> 1

Output: head -> 0 -> 0 -> 1 -> 1 -> 2

Explanation: The values after sorting are [0, 0, 1, 1, 2].

Input: head -> 1 -> 1 -> 1 -> 0

Output: head -> 0 -> 1 -> 1 -> 1

Explanation: The values after sorting are [0, 1, 1, 1].

Input: head -> 2 -> 2 -> 1 -> 2

Constraints

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 2

Hints

  • Use three dummy pointers (zero_head, one_head, two_head) to track separate linked lists for 0s, 1s, and 2s.
  • Traverse the original list and distribute nodes into the corresponding lists. Merge the three lists by updating links: Connect the 0s list → 1s list → 2s list Ensure the tail of the last list points to NULL.

Company Tags

Target Bungie Zoho Snowflake Alibaba Oracle Uber Rockstar Games Activision Blizzard Swiggy Splunk Bain & Company eBay Siemens Healthineers Salesforce Seagate Technology Reddit Chewy Pinterest American Express Visa Ubisoft Texas Instruments Wayfair Roblox Google Microsoft Amazon Meta Apple Netflix Adobe