Sort List (LeetCode 148): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If the list is empty or has one node, it is already sorted, so return it.
- Start
slowatheadandfastathead.next, and advanceslowone step andfasttwo steps whilefastandfast.nextexist. - Set
mid = slow.nextand cut the list withslow.next = None, giving two separate halves. - Recursively sort both halves to get
leftandright. - Merge them: using a dummy node, repeatedly attach the smaller of
left.valandright.val(taking fromlefton ties to keep the sort stable). - Attach whatever remains of
left or rightand returndummy.next.
Step-by-step example
head = [4, 2, 1, 3]
slowstarts at 4 andfastat 2. Sincefast.nextis 1, both move:slowto 2 andfastto 3. Nowfast.nextis null, so the loop stops.midis the node 1, and cutting after 2 gives the halves [4, 2] and [1, 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].
- 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.next1class Solution {
2 public ListNode sortList(ListNode head) {
3 if (head == null || head.next == null) return head;
4 ListNode slow = head, fast = head.next;
5 while (fast != null && fast.next != null) {
6 slow = slow.next;
7 fast = fast.next.next;
8 }
9 ListNode mid = slow.next;
10 slow.next = null;
11 ListNode left = sortList(head);
12 ListNode right = sortList(mid);
13 ListNode dummy = new ListNode(0);
14 ListNode curr = dummy;
15 while (left != null && right != null) {
16 if (left.val <= right.val) {
17 curr.next = left;
18 left = left.next;
19 } else {
20 curr.next = right;
21 right = right.next;
22 }
23 curr = curr.next;
24 }
25 curr.next = left != null ? left : right;
26 return dummy.next;
27 }
28}1class Solution {
2public:
3 ListNode* sortList(ListNode* head) {
4 if (!head || !head->next) return head;
5 ListNode* slow = head;
6 ListNode* fast = head->next;
7 while (fast && fast->next) {
8 slow = slow->next;
9 fast = fast->next->next;
10 }
11 ListNode* mid = slow->next;
12 slow->next = nullptr;
13 ListNode* left = sortList(head);
14 ListNode* right = sortList(mid);
15 ListNode dummy(0);
16 ListNode* curr = &dummy;
17 while (left && right) {
18 if (left->val <= right->val) {
19 curr->next = left;
20 left = left->next;
21 } else {
22 curr->next = right;
23 right = right->next;
24 }
25 curr = curr->next;
26 }
27 curr->next = left ? left : right;
28 return dummy.next;
29 }
30};Time and space complexity
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.
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
fastatheadinstead ofhead.nextleavesslowat 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 = Noneleaves the halves connected, so the recursive call on the left half still sees the whole list. - Advancing
curronly 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 rightloses 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.