Sort List solution explained
To sort a linked list in O(n log n) time, use merge sort: split the list in half with a slow and a fast pointer, sort each half, and merge the two sorted halves by re-linking nodes. Merging lists needs no extra array, which is why merge sort suits linked lists better than quicksort or heapsort. The recursive Sort List solution uses O(log n) stack space; the bottom-up version, which merges runs of 1, 2, 4 and so on, brings extra space down to O(1).
By Evin JohnPublished 7 min read
The task, restated
Given the head of a singly linked list of numbers, return the head of the same nodes arranged in ascending order. The target is O(n log n) time, and the follow-up asks for constant extra memory. Values can repeat and can be negative.
| Input | Output | Note |
|---|---|---|
| 14 → 3 → 9 → 3 → 1 | 1 → 3 → 3 → 9 → 14 | Duplicates stay next to each other |
| -2 → 8 → 0 | -2 → 0 → 8 | Negative values sort normally |
| 5 → 4 → 3 → 2 → 1 | 1 → 2 → 3 → 4 → 5 | Reversed input, still O(n log n) |
| 7 | 7 | One node |
| empty | empty | Return null |
Ask whether rewriting node values is acceptable or whether the nodes themselves must move. Most interviewers expect re-linking, because in real code a node usually carries more than a number. Also ask whether stability matters; merge sort gives it for free if the merge prefers the left run on ties.
How interviewers use it
Sort List combines three linked list skills in one question: finding the middle, cutting a list in two, and merging two sorted lists. It also checks whether you know why merge sort is the natural choice here. Quicksort needs fast access by index for good pivots and partitioning, and heapsort needs an array. Merging, on the other hand, is just pointer moves.
- Constant extra space. Switch from recursion to the bottom-up version below.
- Sort with insertion sort. O(n²) but simple and stable; fine for nearly sorted input.
- Merge k sorted lists. Use a min-heap of list heads, or merge pairs in rounds.
- Sort by a custom key. Change only the comparison inside the merge.
Baseline: copy the values, sort, write back
def sort_by_copy(head):
vals = []
node = head
while node:
vals.append(node.val)
node = node.next
vals.sort()
node = head
for v in vals:
node.val = v
node = node.next
return headIt is a fine first answer to show you have a working solution, but it breaks the spirit of the problem twice: it uses linear memory and it moves values instead of nodes.
Top-down merge sort
Start fast one node ahead of slow so that, for a list of two, slow stops on the first node and the split gives two halves of one node each. Cut after slow, sort both halves recursively, then merge. The merge uses a dummy node so the first comparison needs no special case.
def merge(a, b):
dummy = tail = ListNode()
while a and b:
if a.val <= b.val: # <= keeps equal values in their original order
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.next
def sort_list(head):
if head is None or head.next is None:
return head
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
right = slow.next
slow.next = None
return merge(sort_list(head), sort_list(right))Recursion depth is about log₂ n because every call halves the list, so even a 200,000-node list reached a recursion depth of 19 in our test. The merge itself is a loop, not recursion, which matters: a recursive merge would go n levels deep and overflow on long lists.
Bottom-up merge sort for O(1) extra space
Instead of splitting recursively, treat the list as runs of length 1 and merge each adjacent pair into runs of 2, then 4, then 8, until a single run covers the whole list. Each round walks the list once, cutting off two runs, merging them, and attaching the result to the part already processed. Only a handful of pointers are needed.
function sortList(head) {
let n = 0;
for (let p = head; p; p = p.next) n++;
const dummy = { val: 0, next: head };
for (let width = 1; width < n; width *= 2) {
let prev = dummy, cur = dummy.next;
while (cur) {
const left = cur;
const right = cutAfter(left, width);
cur = cutAfter(right, width);
prev = mergeAfter(prev, left, right);
}
}
return dummy.next;
}
// Detach the first size nodes; return the head of what follows them.
function cutAfter(node, size) {
for (let i = 1; node && i < size; i++) node = node.next;
if (!node) return null;
const rest = node.next;
node.next = null;
return rest;
}
// Merge two sorted runs, hang them after prev, return the last node placed.
function mergeAfter(prev, a, b) {
while (a && b) {
if (a.val <= b.val) { prev.next = a; a = a.next; }
else { prev.next = b; b = b.next; }
prev = prev.next;
}
prev.next = a || b;
while (prev.next) prev = prev.next;
return prev;
}The last line of mergeAfter walks to the end of the merged run so the next pair can be attached there. That walk only covers nodes already merged in this round, so each round stays O(n), and there are about log₂ n rounds.
Time and space
| Approach | Time | Extra space | Stable? |
|---|---|---|---|
| Copy, sort, write back | O(n log n) | O(n) | Yes (values only) |
| Insertion sort on the list | O(n²) | O(1) | Yes |
| Top-down merge sort | O(n log n) | O(log n) recursion | Yes |
| Bottom-up merge sort | O(n log n) | O(1) | Yes |
Edge cases
- Empty and single-node lists return immediately.
- Two nodes: the split must produce one node on each side, or the recursion never shrinks.
- Already sorted, reversed and all-equal input all run in O(n log n).
- Odd lengths in the bottom-up version: the last run of a round may be short or have no partner.
Mistakes to avoid
- Starting slow and fast on the same node with the loop condition fast and fast.next: on two nodes slow ends on the second, the right half is empty, and the recursion never shrinks.
- Forgetting slow.next = None, so the left half still contains the right half.
- Writing the merge recursively, which turns O(log n) stack into O(n) and can overflow.
- Using < instead of <= in the merge and losing stability.
- Saying the recursive version is O(1) space.
How to explain it out loud
Fictional example
- Candidate
- Lists have no random access, so quicksort and heapsort are awkward. Merge sort only needs to split and merge, and merging lists is pointer work with no extra buffer.
- Candidate
- I split with slow and fast pointers, starting fast one ahead so two nodes split into one and one. I cut, recurse on both halves, and merge with a dummy head.
- Candidate
- That is O(n log n) time and O(log n) stack. If you need constant space, I can do it bottom-up: merge runs of size 1, then 2, then 4, walking the list once per round.
Related walkthroughs
Linked List Cycle II is the other place in this set where a slow and fast pointer do the heavy lifting. Odd Even Linked List practices the cut-and-join moves that the merge relies on. Merge Intervals is a problem where sorting first is the whole trick.
Where Natively fits
When you work through sorting problems on a Mac or Windows PC, Natively can read the prompt from a screenshot and write an approach and code, so you can compare its merge loop with yours once your own version is done. A transcript of the mock interview shows whether you explained why merge sort beats quicksort here. See the AI interview assistant page.
Questions people ask
How do you sort a linked list in O(n log n)?
Use merge sort: find the middle with slow and fast pointers, cut the list in two, sort each half, and merge the sorted halves by re-linking nodes.
Why is merge sort preferred for linked lists?
Merging two lists needs no extra array, while quicksort and heapsort depend on fast access by index, which linked lists do not have.
Can you sort a linked list in O(1) extra space?
Yes, with bottom-up merge sort: merge runs of length 1, then 2, then 4 and so on in place. Recursive merge sort uses O(log n) stack.
Is linked list merge sort stable?
Yes, if the merge takes from the left run when values are equal, so equal values keep their original order.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
