Sort List

Pattern: Merging and sorting

medium

Merge sort for a linked list. Split at the middle with slow and fast pointers, sort each half, and merge the two sorted halves. O(n log n), and no arrays.

The problem

Given the head of a linked list, sort it in increasing order and return the head. LeetCode asks for O(n log n) time. For example, 4 → 2 → 1 → 3 becomes 1 → 2 → 3 → 4, and -1 → 5 → 3 → 4 → 0 becomes -1 → 0 → 3 → 4 → 5.

The function name sortList matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Which O(n log n) sort does not need jumping to an index?
  • How do you split a linked list into two halves?
  • Which earlier problem combines two sorted halves?

Hints

    Brute force, and why it fails

    Copy into an array, sort, and write the values back: O(n log n) but O(n) memory. Insertion sort on the list is O(n²). Merge sort on the list is O(n log n) with O(log n) recursion.

    The key insight

    A linked list makes merging cheap (just relink) and splitting easy (slow and fast pointers). That makes merge sort the natural O(n log n) sort for lists.

    Dry run

    4 20 
    1 31 

    The list is 4 → 2 → 1 → 3. Split after the first middle into 4 → 2 and 1 → 3.

    Step 1 of 4

    The plan

    function sortList(head):
        if head is null or head.next is null: return head
        slow = head, fast = head.next
        while fast and fast.next: slow = slow.next; fast = fast.next.next
        right = slow.next; slow.next = null
        return merge(sortList(head), sortList(right))
    

    Complexity

    Time
    O(n log n)
    Space
    O(log n)

    There are log n levels of splitting, and each level merges n nodes. The recursion is log n deep.

    Edge cases

    • Empty or one node: unchanged.
    • Already sorted or reversed: still O(n log n).
    • Repeated values: kept.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode sortList(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode slow = head, fast = head.next;          // split in the middle
            while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
            ListNode right = slow.next;
            slow.next = null;
            return merge(sortList(head), sortList(right));   // sort both halves, then merge
        }
    
        private ListNode merge(ListNode a, ListNode b) {
            ListNode dummy = new ListNode(0), tail = dummy;
            while (a != null && b != null) {
                if (a.val <= b.val) { tail.next = a; a = a.next; }
                else { tail.next = b; b = b.next; }
                tail = tail.next;
            }
            tail.next = a != null ? a : b;
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            if (head == NULL || head->next == NULL) return head;
            ListNode *slow = head, *fast = head->next;       // split in the middle
            while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; }
            ListNode* right = slow->next;
            slow->next = NULL;
            return merge(sortList(head), sortList(right));   // sort both halves, then merge
        }
    
        ListNode* merge(ListNode* a, ListNode* b) {
            ListNode dummy(0);
            ListNode* tail = &dummy;
            while (a != NULL && b != NULL) {
                if (a->val <= b->val) { tail->next = a; a = a->next; }
                else { tail->next = b; b = b->next; }
                tail = tail->next;
            }
            tail->next = a != NULL ? a : b;
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def sortList(self, head: ListNode) -> ListNode:
            if head is None or head.next is None:
                return head
            slow, fast = head, head.next            # split in the middle
            while fast is not None and fast.next is not None:
                slow, fast = slow.next, fast.next.next
            right = slow.next
            slow.next = None
            return self.merge(self.sortList(head), self.sortList(right))   # sort both halves, then merge
    
        def merge(self, a: ListNode, b: ListNode) -> ListNode:
            dummy = tail = ListNode(0)
            while a is not None and b is not None:
                if a.val <= b.val:
                    tail.next, a = a, a.next
                else:
                    tail.next, b = b, b.next
                tail = tail.next
            tail.next = a if a is not None else b
            return dummy.next

    Common mistakes

    • Starting fast on head when splitting, which can leave a two-node list unsplit and recurse forever.
    • Forgetting slow.next = null, so the halves are not separated.
    • Merging without attaching the leftover nodes.

    Similar problems