TRT
Sign in
mediumCoreLeetCode#merge sort#fast and slow pointers

Sort list

Sort a linked list in O(n log n) time with merge sort, splitting at the middle with fast and slow pointers and merging by rewiring nodes.

The Runtime Theory Team1 min read
Taught inMerge sortPro — members onlySplit the array in half, sort each half, merge the two sorted halves. Every level of splitting costs O(n) and there are log n levels, so merge sort is O(n log n) on every input, and it is stable.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inhead = [4, 2, 1, 3]

out[1, 2, 3, 4]

inhead = [-1, 5, 3, 4, 0]

out[-1, 0, 3, 4, 5]

inhead = []

out[]

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

  1. Base case: an empty list or a single node is sorted.
  2. Find the middle with slow and fast pointers, and cut the list in two by setting the middle's next to null. Start fast at head.next so that a two-node list splits evenly.
  3. Sort both halves recursively, then merge them with a dummy head, as in Merge two sorted lists.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save