Sort a Linked List of 0's 1's and 2's

Pattern: Traversal and dummy nodes

easy

Walk the list once and hang each node on one of three chains, for 0s, 1s and 2s, each with its own dummy head. Then join the chains in order. No values are changed and no nodes are created.

The problem

Given the head of a linked list whose values are only 0, 1 and 2, sort it in increasing order by relinking the nodes, and return the new head. Do not create new nodes or change values. For example, 1 → 0 → 2 → 0 → 1 becomes 0 → 0 → 1 → 1 → 2.

The function name sortList matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • With only three possible values, how many groups do you need?
  • How can you build each group without creating nodes?
  • When joining the groups, what if one of them is empty?

Hints

    Brute force, and why it fails

    Count the 0s, 1s and 2s and overwrite the values: O(n), but it changes values, which this problem forbids. Merge sort on the list is O(n log n). Three chains are O(n) and only relink.

    The key insight

    Moving a node to another chain is O(1) in a linked list. So splitting by value into a few chains and joining them is a linear-time sort when there are only a few values.

    Dry run

    10 
    01 
    22 
    03 
    14 
    zeros
    ones
    twos

    The list is 1 → 0 → 2 → 0 → 1. Three empty chains wait, each with a dummy head.

    Step 1 of 4

    The plan

    zero, one, two = dummy heads; z, o, t = their tails
    for each node cur:
        append cur to the chain for cur.val
    t.next = null
    o.next = two.next
    z.next = one.next if it exists else two.next
    return the first non-empty of zero.next, one.next, two.next
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One walk, plus three dummy nodes.

    Edge cases

    • Only 2s and 1s, as in 2 → 1: the 0s chain is empty.
    • Only 0s and 2s: the 1s chain is empty, so 0s link straight to 2s.
    • Empty list: still empty.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode sortList(ListNode head) {
            ListNode zero = new ListNode(0), one = new ListNode(0), two = new ListNode(0);   // dummy heads
            ListNode z = zero, o = one, t = two;    // tails of the three chains
            for (ListNode cur = head; cur != null; cur = cur.next) {
                if (cur.val == 0) { z.next = cur; z = cur; }
                else if (cur.val == 1) { o.next = cur; o = cur; }
                else { t.next = cur; t = cur; }
            }
            t.next = null;                          // the 2s end the list
            o.next = two.next;                      // 1s, then 2s
            z.next = one.next != null ? one.next : two.next;   // 0s, then 1s (or 2s if there are no 1s)
            return zero.next != null ? zero.next : (one.next != null ? one.next : two.next);
        }
    }

    C++

    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            ListNode zero(0), one(0), two(0);       // dummy heads
            ListNode *z = &zero, *o = &one, *t = &two;   // tails of the three chains
            for (ListNode* cur = head; cur != NULL; cur = cur->next) {
                if (cur->val == 0) { z->next = cur; z = cur; }
                else if (cur->val == 1) { o->next = cur; o = cur; }
                else { t->next = cur; t = cur; }
            }
            t->next = NULL;                         // the 2s end the list
            o->next = two.next;                     // 1s, then 2s
            z->next = one.next != NULL ? one.next : two.next;   // 0s, then 1s (or 2s if there are no 1s)
            return zero.next != NULL ? zero.next : (one.next != NULL ? one.next : two.next);
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def sortList(self, head: ListNode) -> ListNode:
            zero, one, two = ListNode(0), ListNode(0), ListNode(0)   # dummy heads
            z, o, t = zero, one, two                # tails of the three chains
            cur = head
            while cur is not None:
                if cur.val == 0:
                    z.next, z = cur, cur
                elif cur.val == 1:
                    o.next, o = cur, cur
                else:
                    t.next, t = cur, cur
                cur = cur.next
            t.next = None                           # the 2s end the list
            o.next = two.next                       # 1s, then 2s
            z.next = one.next if one.next is not None else two.next   # 0s, then 1s (or 2s if there are no 1s)
            if zero.next is not None:
                return zero.next
            return one.next if one.next is not None else two.next

    Common mistakes

    • Forgetting t.next = null, which can leave a cycle through an old pointer.
    • Linking z.next = one.next when there are no 1s, which drops the 2s.
    • Overwriting values instead of relinking.

    Similar problems