SDE & MLE Prep

148. Sort List

Problem

Sort a linked list in ascending order and return its head.

Example: 4→2→1→3 → 1→2→3→4

Constraints: up to 5·10⁴ nodes. Follow-up: O(n log n) time with O(1) memory.

Merge sort is natural for lists: split at the middle (fast/slow), sort halves recursively, merge (21).

Complexity: O(n log n) time, O(log n) recursion.

class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        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 = self.sortList(head), self.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