Given the head of a linked list, return it sorted in ascending order, in O(n log n) time.
Before you code
Quick sort needs random access for good pivots and swaps; merge sort needs only sequential access, and merging lists needs no extra buffer. Merge sort is the natural fit.
Hints
- Base case: an empty list or a single node is sorted.
- Find the middle with slow and fast pointers, and cut the list in two by setting the middle's
nextto null. Startfastathead.nextso that a two-node list splits evenly. - Sort both halves recursively, then merge them with a dummy head, as in Merge two sorted lists.
- Follow-up: the bottom-up version merges runs of length 1, 2, 4… with O(1) extra space.
Production & complexity notes
When solving Sort list on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Merge sort to reinforce the underlying pattern.
What it practices
Divide, conquer and merge, from Merge sort.