LeetCode 148: Sort List Solution
Master LeetCode problem 148 (Sort List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
148. Sort List
Problem Explanation
Explanation
To sort a linked list in O(n logn) time and O(1) space, we can use the merge sort algorithm. The idea is to divide the list into two halves, sort each half recursively, and then merge the sorted halves back together. This approach guarantees the desired time complexity and uses only a constant amount of extra space.
- Splitting: Find the middle of the linked list using the slow and fast pointer technique.
- Recursively sort: Sort the two halves of the list recursively.
- Merge: Merge the two sorted halves back together.
Time complexity: O(n logn)
Space complexity: O(1)
Solution Code
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMiddle(head);
ListNode right = mid.next;
mid.next = null; // break the list
ListNode leftSorted = sortList(head);
ListNode rightSorted = sortList(right);
return merge(leftSorted, rightSorted);
}
private ListNode findMiddle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1 != null) {
current.next = l1;
} else {
current.next = l2;
}
return dummy.next;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 148 (Sort List)?
This page provides optimized solutions for LeetCode problem 148 (Sort List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 148 (Sort List)?
The time complexity for LeetCode 148 (Sort List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 148 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 148 in Java, C++, or Python.