Sort List – Solution & Complexity
Solution Walkthrough
Step 1: Warm up by collecting values, sorting them, and rebuilding the list
A straightforward approach is to walk the linked list once, copy every value into an array, sort that array, and then build a new sorted linked list from those values. This is easy to reason about and still runs in
O(n log n)time, but it usesO(n)extra space for the copied values and rebuilt nodes.Step 2: Use merge sort directly on the linked list for the optimal interview answer
The optimal linked-list solution uses top-down merge sort. Split the list into two halves with slow and fast pointers, recursively sort each half, then merge the two sorted linked lists. Every level touches each node once, so the time complexity is
O(n log n), and the extra space isO(log n)from the recursion stack.