Algorithm-Day34-Sort-List-lc-148
π§© Problem Description
Given the head
of a linked list, return the list sorted in ascending order.
You must sort in O(n log n) time and use constant space complexity (no array conversion).
π¬ Example
1 | Input: head = [4,2,1,3] |
π‘ Intuition
We cannot use extra space like arrays. So we apply merge sort on the linked list itself:
- Split the list into halves using the slow/fast pointer technique
- Recursively sort each half
- Merge the two sorted halves (like in
lc-21
)
This gives us O(n log n) time and uses O(1) extra space for list nodes.
π’ Java Code (Top-Down Merge Sort)
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n log n)
- Space Complexity: O(log n) due to recursion stack (not extra list memory)
βοΈ Summary
- Use top-down merge sort directly on the list.
- Core techniques:
- Fast/slow pointer to find middle
- Recursive divide-and-conquer
- Merging two sorted linked lists
- Efficient, in-place sorting without using arrays
Make sure youβve mastered
lc-21
(merge two sorted lists) before this one β itβs the foundation of merging steps here.