Sort List
Medium
Topics
Given the head of a linked list, return the list sorted in ascending order.
Example 1
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Constraints
- 0 <= number of nodes <= 5*10^4
- -10^5 <= Node.val <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Sorting a linked list in O(n log n) without random access points at merge sort: splitting a list is cheap, and merging two sorted lists is a pointer walk. The usual presentation is top-down — find the middle, recurse, merge — which is O(log n) call frames.
The shown solution is bottom-up, which removes the recursion entirely. Merge adjacent runs of length 1, then of length 2, then 4, doubling until the run length covers the list. Same O(n log n), same stability, but O(1) auxiliary space and no stack-depth exposure at the stated bound of 5×10⁴ nodes.
Collecting the values into an array, sorting that, and writing them back is also O(n log n) and is a legitimate pragmatic answer — but it costs O(n) space and never touches a pointer, so it sidesteps everything this problem examines.
Approach
- Count the nodes to get
n, and put a dummy in front so the head can change. - For each
widthin 1, 2, 4, ... whilewidth < n, walk the list taking two consecutive runs of that length. cut(head, k)keepsknodes, detaches the rest, and returns the remainder — so two cuts isolate the left run, the right run, and the position to resume from.- Merge the two runs onto the tail built so far, and carry the new tail forward as the next
prev. - Return
dummy.next.
Dry Run
input 4 -> 2 -> 1 -> 3 n = 4
width 1 runs (4)(2) and (1)(3)
merge -> 2 -> 4, then 1 -> 3
list is now 2 -> 4 -> 1 -> 3
width 2 runs (2 4)(1 3)
merge -> 1 -> 2 -> 3 -> 4
width 4 not less than n, stop
answer 1 -> 2 -> 3 -> 4
verified against sorted() on 300 random lists up to length 60, plus
[] -> []
[1] -> [1]
[5,5,5] -> [5,5,5] equal keys keep input order
[-1,5,3,4,0] -> [-1,0,3,4,5]Complexity
- Time — O(n log n): there are
log₂ndoubling rounds and each round walks and merges every node once. - Space — O(1): a dummy and a few pointers. Nothing is copied and there is no recursion, which is the whole reason to prefer bottom-up here.
- The top-down version is the same time bound but O(log n) stack frames; the collect-and-sort version is O(n) space.
Common Pitfalls
- Sorting the values and writing them back. It produces a correctly ordered list and it is what the page used to ship, but it neither merge-sorts nor relinks, so it answers a different question than the one the problem tags advertise.
- Using
<rather than<=in the merge. Merge sort's stability depends on preferring the left run when keys tie; with<equal elements swap order. - Forgetting to null-terminate when cutting. If
cutdoes not severhead.next, the "two runs" are still one list and the merge walks past its own boundary. - Failing to advance the tail to the actual end after a merge. When one run is exhausted the remainder is attached wholesale, so the new tail is at the end of that remainder, not where the comparison loop stopped.
- Quicksort on a linked list. Partitioning is fine but the pivot choice has no random access, so the worst case is O(n²) with no cheap mitigation.
- Finding the middle with a slow and fast pointer in the top-down version and forgetting to cut the first half loose, which recurses on the whole list forever.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head):
if not head or not head.next:
return head
n = 0
cur = head
while cur:
n += 1
cur = cur.next
# Bottom-up merge sort: merge runs of 1, then 2, then 4 ... No recursion,
# so no O(log n) call stack, and the nodes themselves are relinked.
dummy = ListNode(0, head)
width = 1
while width < n:
prev = dummy
cur = dummy.next
while cur:
left = cur
right = self._cut(left, width)
cur = self._cut(right, width)
prev = self._merge(left, right, prev)
width *= 2
return dummy.next
def _cut(self, head, k):
"""Keep k nodes from head, detach the rest and return the remainder."""
while k > 1 and head:
head = head.next
k -= 1
if not head:
return None
rest = head.next
head.next = None
return rest
def _merge(self, a, b, tail):
"""Append the merge of a and b after tail; return the new tail."""
cur = tail
while a and b:
if a.val <= b.val: # <= keeps the sort stable
cur.next = a
a = a.next
else:
cur.next = b
b = b.next
cur = cur.next
cur.next = a if a else b
while cur.next:
cur = cur.next
return curimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
int n = 0;
for (ListNode c = head; c != null; c = c.next) n++;
// Bottom-up merge sort: merge runs of 1, then 2, then 4 ... No recursion,
// so no O(log n) call stack, and the nodes themselves are relinked.
ListNode dummy = new ListNode(0);
dummy.next = head;
for (int width = 1; width < n; width *= 2) {
ListNode prev = dummy, cur = dummy.next;
while (cur != null) {
ListNode left = cur;
ListNode right = cut(left, width);
cur = cut(right, width);
prev = merge(left, right, prev);
}
}
return dummy.next;
}
private ListNode cut(ListNode head, int k) {
while (k > 1 && head != null) {
head = head.next;
k--;
}
if (head == null) return null;
ListNode rest = head.next;
head.next = null;
return rest;
}
private ListNode merge(ListNode a, ListNode b, ListNode tail) {
ListNode cur = tail;
while (a != null && b != null) {
if (a.val <= b.val) { // <= keeps the sort stable
cur.next = a;
a = a.next;
} else {
cur.next = b;
b = b.next;
}
cur = cur.next;
}
cur.next = (a != null) ? a : b;
while (cur.next != null) cur = cur.next;
return cur;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
ListNode* cut(ListNode* head, int k) {
while (k > 1 && head) {
head = head->next;
k--;
}
if (!head) return nullptr;
ListNode* rest = head->next;
head->next = nullptr;
return rest;
}
ListNode* merge(ListNode* a, ListNode* b, ListNode* tail) {
ListNode* cur = tail;
while (a && b) {
if (a->val <= b->val) { // <= keeps the sort stable
cur->next = a;
a = a->next;
} else {
cur->next = b;
b = b->next;
}
cur = cur->next;
}
cur->next = a ? a : b;
while (cur->next) cur = cur->next;
return cur;
}
public: ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
int n = 0;
for (ListNode* c = head; c; c = c->next) n++;
// Bottom-up merge sort: merge runs of 1, then 2, then 4 ... No recursion,
// so no O(log n) call stack, and the nodes themselves are relinked.
ListNode dummy(0);
dummy.next = head;
for (int width = 1; width < n; width *= 2) {
ListNode* prev = &dummy;
ListNode* cur = dummy.next;
while (cur) {
ListNode* left = cur;
ListNode* right = cut(left, width);
cur = cut(right, width);
prev = merge(left, right, prev);
}
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {ListNode}
*/ var sortList = function(head) {
if (!head || !head.next) return head;
let n = 0;
for (let c = head; c; c = c.next) n++;
// Keep k nodes from h, detach the rest and return the remainder.
const cut = (h, k) => {
while (k > 1 && h) {
h = h.next;
k--;
}
if (!h) return null;
const rest = h.next;
h.next = null;
return rest;
};
// Append the merge of a and b after tail; return the new tail.
const merge = (a, b, tail) => {
let cur = tail;
while (a && b) {
if (a.val <= b.val) { // <= keeps the sort stable
cur.next = a;
a = a.next;
} else {
cur.next = b;
b = b.next;
}
cur = cur.next;
}
cur.next = a ? a : b;
while (cur.next) cur = cur.next;
return cur;
};
// Bottom-up merge sort: merge runs of 1, then 2, then 4 ... No recursion,
// so no O(log n) call stack, and the nodes themselves are relinked.
const dummy = new ListNode(0, head);
for (let width = 1; width < n; width *= 2) {
let prev = dummy, cur = dummy.next;
while (cur) {
const left = cur;
const right = cut(left, width);
cur = cut(right, width);
prev = merge(left, right, prev);
}
}
return dummy.next;
};