Sort List (LeetCode 148): Solution and Explanation

Medium
Linked List
Two Pointers
Divide And Conquer
Sorting
Merge Sort

Given the head of a singly linked list, return the list sorted in ascending order. The target is O(n log n) time, which rules out the quadratic sorts that are natural on lists.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The easy way out is to copy the values into an array, sort the array and write the values back. It works, but it costs O(n) extra memory and dodges the point of the problem, which is to sort the nodes themselves. Insertion sort works directly on a list but is O(n²) in the worst case.

Merge sort is the sort that fits linked lists best. Quicksort and heapsort depend on random access, which a list does not have, but merge sort only needs two things: splitting a list into halves and merging two sorted lists. Merging is especially natural on lists because you just relink nodes, with no auxiliary array like the array version needs.

To split, you find the middle with the slow and fast pointer trick. Starting fast one node ahead of slow makes slow stop at the end of the first half, so you can cut the list with slow.next = None. Then sort each half recursively and merge them with a dummy head node, which removes the special case of choosing the first node of the result.

Approach: Top-down merge sort on the list

  1. If the list is empty or has one node, it is already sorted, so return it.
  2. Start slow at head and fast at head.next, and advance slow one step and fast two steps while fast and fast.next exist.
  3. Set mid = slow.next and cut the list with slow.next = None, giving two separate halves.
  4. Recursively sort both halves to get left and right.
  5. Merge them: using a dummy node, repeatedly attach the smaller of left.val and right.val (taking from left on ties to keep the sort stable).
  6. Attach whatever remains of left or right and return dummy.next.

Step-by-step example

head = [4, 2, 1, 3]
  1. slow starts at 4 and fast at 2. Since fast.next is 1, both move: slow to 2 and fast to 3. Now fast.next is null, so the loop stops.
  2. mid is the node 1, and cutting after 2 gives the halves [4, 2] and [1, 3].
  3. Sorting [4, 2] splits into [4] and [2], which merge to [2, 4]. Sorting [1, 3] splits into [1] and [3], which merge to [1, 3].
  4. Merging [2, 4] and [1, 3]: take 1, then 2, then 3, and the leftover 4 is appended, giving [1, 2, 3, 4].

Code: Python, Java, C++

1class Solution:
2    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
3        if not head or not head.next:
4            return head
5        # Find middle using slow/fast pointers
6        slow, fast = head, head.next
7        while fast and fast.next:
8            slow = slow.next
9            fast = fast.next.next
10        mid = slow.next
11        slow.next = None
12        # Recursively sort both halves
13        left = self.sortList(head)
14        right = self.sortList(mid)
15        # Merge sorted halves
16        dummy = ListNode(0)
17        curr = dummy
18        while left and right:
19            if left.val <= right.val:
20                curr.next = left
21                left = left.next
22            else:
23                curr.next = right
24                right = right.next
25            curr = curr.next
26        curr.next = left or right
27        return dummy.next

Time and space complexity

Time

O(n log n)

The list is halved about log n times, and at each level of recursion the merges together touch all n nodes, so the total is n log n.

Space

O(log n)

Merging only relinks nodes, so no new nodes are allocated, but the recursion is about log n levels deep and each level keeps a stack frame.

Other approaches

Bottom-up merge sort (time O(n log n), space O(1))

Merge runs of size 1, then 2, then 4 and so on, iterating over the list each pass and splicing merged runs together. It removes recursion and achieves the true O(1) extra space that the follow up asks for, at the cost of more pointer bookkeeping.

Copy to an array and sort (time O(n log n), space O(n))

Read the values into an array, sort it with the built-in sort and write the values back into the nodes. Simple and fast in practice, but it uses linear extra memory.

Common mistakes

  • Starting fast at head instead of head.next leaves slow at the second node of a two-node list, so the split produces an empty half and the same list again, recursing forever.
  • Forgetting slow.next = None leaves the halves connected, so the recursive call on the left half still sees the whole list.
  • Advancing curr only inside one branch of the merge loop drops or duplicates nodes; it must move after every attachment.
  • Forgetting to attach the remaining tail with curr.next = left or right loses the larger elements at the end.

Frequently asked questions

Why is merge sort preferred for linked lists?

Merge sort only needs sequential access, and merging two lists is just relinking pointers with no extra buffer. Quicksort and heapsort rely on fast random access, which linked lists cannot provide.

Does this solution use O(1) space?

Not strictly. The merging uses constant extra memory, but the top-down recursion uses O(log n) stack frames. A bottom-up iterative merge sort meets the constant space requirement.

How do you find the middle of a linked list?

Move a slow pointer one step and a fast pointer two steps at a time. When the fast pointer reaches the end, the slow pointer is at the middle, and starting fast one node ahead makes slow land at the end of the first half.

Is the sort stable?

Yes. When values are equal the merge takes the node from the left half first, so equal elements keep their original relative order.