LeetCode #148 Medium

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.
Constraints
  • The number of nodes in the list is in the range [0, 5 * 10⁴].
  • -10⁵ <= Node.val <= 10⁵
linked-listsortingmerge-sort
Open on LeetCode ↗
02

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²).

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sortList(self, head):
▶3 if not head or not head.next:
▶4 return head
▶5 slow, fast = head, head.next
▶6 while fast and fast.next:
▶7 slow = slow.next
▶8 fast = fast.next.next
▶9 right = slow.next
▶10 slow.next = None
▶11 return self.merge(self.sortList(head), self.sortList(right))
▶12 
▶13 def merge(self, a, b):
▶14 dummy = tail = ListNode()
▶15 while a and b:
▶16 if a.val <= b.val:
▶17 tail.next, a = a, a.next
▶18 else:
▶19 tail.next, b = b, b.next
▶20 tail = tail.next
▶21 tail.next = a or b
▶22 return dummy.next
42134213middle found → cut after 2
left4 → 2
right1 → 3
The slow pointer stops on 2, the last node of the first half. Setting its next to null splits 4 → 2 → 1 → 3 into 4 → 2 and 1 → 3, two separate lists that each recursive call can sort on its own.
4213421342middle found → cut after 4
left4
right2
The slow pointer stops on 4, the last node of the first half. Setting its next to null splits 4 → 2 into 4 and 2, two separate lists that each recursive call can sort on its own.
4213421342one node → already sorted
head4single node
A list of one node is sorted by definition, so this call returns 4 as it is. This base case is what stops the splitting.
4213421342one node → already sorted
head2single node
A list of one node is sorted by definition, so this call returns 2 as it is. This base case is what stops the splitting.
42132134a22 < 4 → link 2 next
merged2
Compare the two heads, 4 and 2. Both halves are sorted, so the smaller head is the smallest value left anywhere: link 2 to the tail of the merged list.
42132413one side empty → attach 4
merged2 → 4
The right half has run out. What is left of the other half, 4, is already sorted and no smaller than anything merged so far, so one link attaches all of it. This call returns 2 → 4.
4213241313middle found → cut after 1
left1
right3
The slow pointer stops on 1, the last node of the first half. Setting its next to null splits 1 → 3 into 1 and 3, two separate lists that each recursive call can sort on its own.
4213241313one node → already sorted
head1single node
A list of one node is sorted by definition, so this call returns 1 as it is. This base case is what stops the splitting.
4213241313one node → already sorted
head3single node
A list of one node is sorted by definition, so this call returns 3 as it is. This base case is what stops the splitting.
421324113b1 < 3 → link 1 next
merged1
Compare the two heads, 1 and 3. Both halves are sorted, so the smaller head is the smallest value left anywhere: link 1 to the tail of the merged list.
42132413one side empty → attach 3
merged1 → 3
The left half has run out. What is left of the other half, 3, is already sorted and no smaller than anything merged so far, so one link attaches all of it. This call returns 1 → 3.
124a13b1 < 2 → link 1 next
merged1
Compare the two heads, 2 and 1. Both halves are sorted, so the smaller head is the smallest value left anywhere: link 1 to the tail of the merged list.
1224a13b2 < 3 → link 2 next
merged1 → 2
Compare the two heads, 2 and 3. Both halves are sorted, so the smaller head is the smallest value left anywhere: link 2 to the tail of the merged list.
12324a133 < 4 → link 3 next
merged1 → 2 → 3
Compare the two heads, 4 and 3. Both halves are sorted, so the smaller head is the smallest value left anywhere: link 3 to the tail of the merged list.
1234one side empty → attach 4
merged1 → 2 → 3 → 4
The right half has run out. What is left of the other half, 4, is already sorted and no smaller than anything merged so far, so one link attaches all of it. This call returns 1 → 2 → 3 → 4.
1234sorted: 1 → 2 → 3 → 4
head1new first node
The top call has merged its two sorted halves, so the whole list is in order: 1 → 2 → 3 → 4. No node was copied; only next pointers changed.
05

Common pitfalls

Starting fast at head

✗ Wrong
slow, fast = head, head
✓ Right
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

✗ Wrong
right = slow.next
left = self.sortList(head)
✓ Right
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

✗ Wrong
def merge(a, b):
    if a.val <= b.val:
        a.next = merge(a.next, b)
        return a
    ...
✓ Right
while a and b:
    ...
    tail = tail.next

A 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.

06

Edge cases

An empty list

head is null, so the first check returns it straight away. There is nothing to split or merge.

07

Complexity

Time
O(n log n)
Space
O(log n)
Halving gives about log n levels of calls, and the merges on each level touch every node once. The only extra memory is the call stack, which is about 16 frames deep for 50,000 nodes; merging itself just relinks nodes.
08

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.