Problem
Problem page: https://leetcode.com/problems/sort-list/
Topics: Linked List, Sort
Difficulty: Medium
Similar problems: (E) Merge Two Sorted Lists, (M) Sort Colors, (M) Insertion Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Analysis
Merge sort on a linked list. findMiddle uses fast and slow pointers to find the midpoint: slow starts at head and fast starts at head.next. Each time, fast moves two steps and slow moves one. When fast reaches the end, slow is at the last node of the first half. With an even number of nodes, the halves are the same length; with an odd number, the first half has one extra node.
mergeList splits the list at the midpoint (mid.next = None), sorts each half by calling mergeList recursively, then joins the halves into one list with the standard merge for two sorted linked lists. It starts the merged list with the dummy node new_head and appends the smaller of the two current nodes at each step. Finally, it attaches the remaining segment to the end in one go and returns new_head.next.
There are log n levels, and the total time spent finding midpoints and merging is O(n) per level, so the time complexity is O(n log n). Array merge sort needs an O(n) auxiliary array for the merge, but the linked-list version doesn't need one because it only changes the next pointers. But this is top-down recursion, and the recursion stack is about log n levels deep. That makes the extra space O(log n), so strictly speaking, it doesn't meet the problem's constant-space requirement.
To get the extra space down to O(1), I'd have to switch to bottom-up iterative merge sort: first merge adjacent runs of length 1 in pairs, then do the same with runs of length 2, 4, 8 and so on, without recursion. I didn't write my code that way.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-sort-list/
