Skip to content

visual walkthrough

Sort List

MediumMerge Sort on ListsReported at: MetaAmazonMicrosoft+2

Merge sort on a linked list in O(n log n).

Solve on LeetCode

The idea

Quick sort and heap sort need jumps to any position, which lists can't do. Merge sort only needs to split in half and to merge, and both are natural on a list.

Split with slow and fast pointers, sort each half the same way, then merge them like Merge Two Sorted Lists.

Complexity

approachtimespace
Copy, sort, write backO(n log n)O(n)
Merge sort on the listO(n log n)O(log n)

More walkthroughs