Merge Sort for Linked List

medium

Given the head of a singly linked list, sort its nodes into non-decreasing order and return the head of the sorted list — using the merge sort algorithm.

Merge sort is the natural fit for a linked list: unlike an array, a list can't jump to its middle in O(1), but it can be split and rewoven purely by rearranging next pointers. Your job is to sort by relinking nodes, not by shuffling values around, and to do it in O(n log n) time.

The list may be empty. Return the new head after sorting.

Hints

Arrays let you jump to the middle in one step; a linked list doesn't. Which classic sort only ever splits a sequence and stitches it back together?
You already know how to merge two sorted lists in one linear pass. If both halves came back sorted, the merge finishes the job — so how do you get two halves?
Find the middle with slow/fast pointers, cut the list there, recurse on each half, then merge the two sorted halves.

Common doubts

Merge sort needs only sequential access and splits/merges by relinking pointers, so it's a natural fit. Quicksort relies on cheap random access for partitioning, which a linked list lacks, and its worst case is quadratic.
The intended solution rearranges nodes by relinking next. Copying values into an array and sorting also works but uses O(n) extra space and ignores the list structure the problem is testing.
For an even-length list it makes slow stop at the end of the first half, giving a clean split. Starting fast at head can leave a two-node list unsplit, causing infinite recursion.

Interview follow-ups

Yes — bottom-up merge sort iterates over run sizes 1, 2, 4, ... merging adjacent runs each pass. It's O(n log n) time and true O(1) extra space.
Use a min-heap of the k current heads (O(n log k)), or repeatedly merge lists in pairs — the same divide-and-conquer shape as this problem.

Fun facts

  • Merge sort's split-and-merge is one of the few sorts that's naturally stable and works beautifully on data you can only read sequentially — which is exactly a linked list.
  • The same bottom-up merging idea powers external sorting: sorting files far larger than memory by merging sorted chunks streamed from disk.

Asked at

AmazonMicrosoftGoogleAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: head = [9,5,2,8]
Output: [2,5,8,9]
The four values rearranged into non-decreasing order.
Example 2
Input: head = [40,20,10,60,50,30]
Output: [10,20,30,40,50,60]
Sorting the list yields the values in increasing order.
Constraints

- 0 <= number of nodes <= 10^5 - 0 <= Node.val <= 10^6

Solve this problem →