The 30 second answer
I merge-sort the list so the sort stays O(n log n) time and O(1) extra memory besides the recursion, or O(log n) stack. I split the list in half with slow and fast pointers, sort each half, and merge the two sorted lists with the same dummy-head merge used earlier.
Problem Given the head of a linked list, return the list sorted in ascending order. The official brief asks for O(n log n) time and constant extra space, or as close as a clean merge sort can get. Original: LeetCode 148: Sort List.
Understanding the prompt You cannot reach for Arrays.sort after copying values if you must keep O(1) extra memory and rearrange the nodes themselves. Quicksort on a list has a poor worst case and awkward partitioning. Merge sort is the natural list sort, because splitting and merging do not need random access.
Pattern recognition Merge sort, using fast and slow pointers to split and the merge-two-sorted routine to combine.
Brute force Copy values to an array, sort, and write them back: O(n log n) time but O(n) extra space, and it is not a list algorithm.
Optimal If the list is empty or a single node, return it. Otherwise walk slow and fast, keeping the node before slow, to cut the list into two halves: prev.next = null. Recursively sort each half and merge them. The split must actually detach the halves, otherwise the recursion does not terminate.
Alternatives Bottom-up merge sort with iteratively growing run sizes is the true O(1)-space version, because it avoids the recursive stack. It is longer to write; mention it if the interviewer is strict about the stack frames.
Java solution
public class SortList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
static ListNode list(int... a) {
var dummy = new ListNode(0);
var t = dummy;
for (int x : a) {
t.next = new ListNode(x);
t = t.next;
}
return dummy.next;
}
static String str(ListNode h) {
var sb = new StringBuilder("[");
for (ListNode p = h; p != null; p = p.next) {
if (sb.length() > 1) sb.append(", ");
sb.append(p.val);
}
return sb.append("]").toString();
}
static ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null, slow = head, fast = head;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
return merge(sortList(head), sortList(slow));
}
static ListNode merge(ListNode a, ListNode b) {
var dummy = new ListNode(0);
var t = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { t.next = a; a = a.next; }
else { t.next = b; b = b.next; }
t = t.next;
}
t.next = a != null ? a : b;
return dummy.next;
}
public static void main(String[] args) {
System.out.println(str(sortList(list(4, 2, 1, 3)))); // [1, 2, 3, 4]
System.out.println(str(sortList(list(-1, 5, 3, 4, 0)))); // [-1, 0, 3, 4, 5]
System.out.println(str(sortList(null))); // []
}
}Complexity O(n log n) time. O(log n) extra space for the recursion, or O(1) if you write the bottom-up form.
Edge cases
- Official samples: [4,2,1,3] becomes [1,2,3,4]; [-1,5,3,4,0] becomes [-1,0,3,4,5].
- An empty list or a single node is already sorted.
- Already sorted or reverse-sorted inputs.
Follow-ups
- Merge k sorted lists, if each run is already sorted.
- Bottom-up merge sort if constant auxiliary space is required strictly.
Tests [4,2,1,3] becomes [1,2,3,4]. [-1,5,3,4,0] becomes [-1,0,3,4,5]. An empty list stays empty.
How to say it in the interview "Linked lists merge well, so I merge-sort: split in half with slow and fast pointers, sort each half, and merge with a dummy head. That is n log n time. The recursive version uses log n stack frames; a bottom-up loop would be constant extra space."
Sources (1)
- LeetCode 148: Sort Listleetcode.com