Sort List
Sort List is LeetCode 148 (Medium). Given the head of a singly linked list, return the list sorted in ascending order.
- The list can hold 50,000 nodes, so a quadratic method such as insertion sort is too slow.
- Follow-up: O(n log n) time with O(1) extra memory.
- The number of nodes in the list is in the range [0, 5 * 10⁴].
- -10⁵ <= Node.val <= 10⁵
Intuition
Merge sort suits a linked list even better than an array. It only ever walks forward, and merging two sorted lists needs no extra buffer: you relink the nodes you already have.
- Split: slow and fast pointers find the middle, then the link after it is cut.
- Sort: each half the same way, down to single nodes.
- Merge: keep linking the smaller of the two heads.
Quicksort, the usual array choice, wants random access to pick good pivots, and with the first node as pivot an already sorted list costs O(n²).
To sort a linked list in O(n log n), reach for merge sort. It reuses two smaller problems: Middle of the Linked List for the split and Merge Two Sorted Lists for the merge.
Approach
Before reading on, write the split: given a list of at least two nodes, return the head of its second half and leave the first half ending in null. Check it on a two-node list; that is where most splits go wrong.
Stop at zero or one node
If head is null or has no next node, return it. Such a list is already sorted, and this check is what ends the recursion.
Find the end of the first half
Start slow at head and fast at head.next, then move slow one step and fast two while fast and fast.next exist. Starting fast one node ahead makes slow stop on the last node of the first half, so even two nodes split one and one.
Cut, then sort both halves
Save right = slow.next and set slow.next = None. The two halves are now separate lists, each strictly shorter than before, so the two recursive calls are guaranteed to finish.
Merge by relinking
Start tail at a dummy node. While both lists have nodes, link the smaller head to tail and step forward, taking from the left list on a tie. When one list runs out, link the rest of the other in one step and return dummy.next.
Code in Python, C++ and Java
Common pitfalls
Starting fast at head
slow, fast = head, head
slow, fast = head, head.next
On the two-node list 2 → 1, slow moves to the second node before fast runs off the end. Cutting after it leaves the left half as the whole list and the right half empty, so the call repeats on the same two nodes forever.
Leaving the halves joined
right = slow.next left = self.sortList(head)
right = slow.next slow.next = None left = self.sortList(head)
Without the cut, the first half still runs to the end of the list. On 4 → 2 → 1 → 3 the left call receives all four nodes again and the recursion never shrinks.
Merging with recursion
def merge(a, b):
if a.val <= b.val:
a.next = merge(a.next, b)
return a
...while a and b:
...
tail = tail.nextA recursive merge goes one call deeper per node it links. Merging two halves of a 50,000-node list needs 50,000 nested calls, far past Python's default limit of about 1,000, so the largest tests crash.
Edge cases
head is null, so the first check returns it straight away. There is nothing to split or merge.
Complexity
Sort List FAQ
How do you meet the O(1) memory follow-up?
Use bottom-up merge sort. Walk the list merging runs of length 1 into sorted pairs, then pairs into runs of 4, then 8, until one run covers the whole list. A loop replaces the recursion, so only a few pointers are kept. The code is longer, and most interviewers accept the top-down version with its O(log n) stack.
Why not copy the values into an array and sort that?
It works and runs in O(n log n) time, but it needs O(n) extra memory and rewrites values instead of moving nodes. If nodes carried other data, or other code held pointers to them, overwriting values would be wrong.