sagelearnai

Sort List

Difficulty: Medium · Pattern: Linked List · LeetCode #148

Sort a linked list in ascending order in O(n log n) time.

Examples

text
4 → 2 → 1 → 3        →  1 → 2 → 3 → 4
−1 → 5 → 3 → 4 → 0   →  −1 → 0 → 3 → 4 → 5

Hints

  1. Merge sort suits linked lists: merging needs no extra arrays, and splitting is easy with fast/slow pointers.

Approach

Recursively: if the list has 0 or 1 nodes, return it. Find the middle with slow/fast pointers (fast starting at head.next, so slow stops at the end of the first half), cut the list there, sort both halves, and merge them (as in Merge Two Sorted Lists). O(n log n) time; O(log n) recursion stack (a bottom-up iterative version achieves O(1)).

Complexity

Time: O(n log n). Space: O(log n) recursion.

Python solution
def sortList(head):
    if not head or not head.next:
        return head
    slow, fast = head, head.next
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    mid, slow.next = slow.next, None
    a, b = sortList(head), sortList(mid)
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next
JavaScript solution
function sortList(head) {
  if (!head || !head.next) return head;
  let slow = head, fast = head.next;
  while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
  const mid = slow.next; slow.next = null;
  let a = sortList(head), b = sortList(mid);
  const dummy = new ListNode(); let tail = dummy;
  while (a && b) { if (a.val <= b.val) { tail.next = a; a = a.next; } else { tail.next = b; b = b.next; } tail = tail.next; }
  tail.next = a || b; return dummy.next;
}