Quicksort for Linked Lists

Pattern: Merging and sorting

medium

Take the head's value as the pivot and split the list into three chains, less, equal and greater, by relinking. Sort the less and greater chains the same way, then join less, equal, greater.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Sort a linked list in increasing order using quicksort, by relinking nodes, and return the head. For example, 30 → 3 → 4 → 20 → 5 becomes 3 → 4 → 5 → 20 → 30.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name quickSort is this guide's own, as is the choice of the first node as pivot with a three-way split.

Think first

  • Array quicksort swaps values around a pivot. What is easier on a linked list?
  • Why split into three groups instead of two?
  • After sorting the parts, how do you join them?

Hints

    Brute force, and why it fails

    Copy values into an array, sort, write back: O(n log n) with O(n) memory. Quicksort on the list is O(n log n) on average but O(n²) when the pivot is always the smallest or largest (sorted input). Merge sort (Sort List) avoids that worst case.

    The key insight

    On a linked list, partitioning is easier than on an array: moving a node to another chain is one pointer change. A three-way split also keeps many equal values from making the recursion deep.

    Dry run

    300 
    31 
    42 
    203 
    54 
    pivot30

    The list is 30 → 3 → 4 → 20 → 5. The pivot is 30.

    Step 1 of 4

    The plan

    function quickSort(head):
        if head is null or head.next is null: return head
        pivot = head.val
        split all nodes into less, equal, greater chains; end each with null
        left = quickSort(less), right = quickSort(greater)
        end of equal points to right
        if left is null: return equal
        end of left points to equal
        return left
    

    Complexity

    Time
    O(n log n) average, O(n²) worst
    Space
    O(log n) average

    Each level of recursion splits all nodes once. With a poor pivot every time, there are n levels. The recursion stack is the extra memory.

    Edge cases

    • Empty or one node: unchanged.
    • All equal: one split finishes it.
    • Already sorted: the worst case, n levels deep.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode quickSort(ListNode head) {
            if (head == null || head.next == null) return head;
            int pivot = head.val;
            ListNode less = new ListNode(0), equal = new ListNode(0), greater = new ListNode(0);   // dummy heads
            ListNode l = less, e = equal, g = greater;
            for (ListNode cur = head; cur != null; cur = cur.next) {   // three-way split around the pivot
                if (cur.val < pivot) { l.next = cur; l = cur; }
                else if (cur.val == pivot) { e.next = cur; e = cur; }
                else { g.next = cur; g = cur; }
            }
            l.next = null; e.next = null; g.next = null;
            ListNode left = quickSort(less.next), right = quickSort(greater.next);
            e.next = right;                         // pivots, then the sorted greater part
            if (left == null) return equal.next;
            ListNode t = left;
            while (t.next != null) t = t.next;      // end of the sorted smaller part
            t.next = equal.next;
            return left;
        }
    }

    C++

    class Solution {
    public:
        ListNode* quickSort(ListNode* head) {
            if (head == NULL || head->next == NULL) return head;
            int pivot = head->val;
            ListNode less(0), equal(0), greater(0);  // dummy heads
            ListNode *l = &less, *e = &equal, *g = &greater;
            for (ListNode* cur = head; cur != NULL; cur = cur->next) {   // three-way split around the pivot
                if (cur->val < pivot) { l->next = cur; l = cur; }
                else if (cur->val == pivot) { e->next = cur; e = cur; }
                else { g->next = cur; g = cur; }
            }
            l->next = NULL; e->next = NULL; g->next = NULL;
            ListNode* left = quickSort(less.next);
            ListNode* right = quickSort(greater.next);
            e->next = right;                        // pivots, then the sorted greater part
            if (left == NULL) return equal.next;
            ListNode* t = left;
            while (t->next != NULL) t = t->next;    // end of the sorted smaller part
            t->next = equal.next;
            return left;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def quickSort(self, head: ListNode) -> ListNode:
            if head is None or head.next is None:
                return head
            pivot = head.val
            less, equal, greater = ListNode(0), ListNode(0), ListNode(0)   # dummy heads
            l, e, g = less, equal, greater
            cur = head
            while cur is not None:                  # three-way split around the pivot
                if cur.val < pivot:
                    l.next, l = cur, cur
                elif cur.val == pivot:
                    e.next, e = cur, cur
                else:
                    g.next, g = cur, cur
                cur = cur.next
            l.next = e.next = g.next = None
            left, right = self.quickSort(less.next), self.quickSort(greater.next)
            e.next = right                          # pivots, then the sorted greater part
            if left is None:
                return equal.next
            t = left
            while t.next is not None:               # end of the sorted smaller part
                t = t.next
            t.next = equal.next
            return left

    Common mistakes

    • Forgetting to end the chains with null, which leaves old links and cycles.
    • Using a two-way split with the pivot inside one side, which can recurse forever on equal values.
    • Walking to the end of "less" before it has been sorted.

    Similar problems