Sort List - Problem
You are given the head of a singly linked list containing integers. Your task is to sort the entire linked list in ascending order and return the head of the sorted list.
The challenge here is that unlike arrays, linked lists don't provide random access to elements. You can only traverse them sequentially, which makes traditional sorting algorithms like quicksort less efficient. The optimal solution should achieve O(n log n) time complexity while using only O(log n) space for recursion.
Example: Given a linked list 4 → 2 → 1 → 3, you should return 1 → 2 → 3 → 4.
Input & Output
example_1.py — Basic Sorting
$
Input:
head = [4,2,1,3]
›
Output:
[1,2,3,4]
💡 Note:
The linked list contains nodes with values 4->2->1->3. After sorting in ascending order, we get 1->2->3->4.
example_2.py — Already Sorted
$
Input:
head = [1,2,3,4,5]
›
Output:
[1,2,3,4,5]
💡 Note:
The linked list is already sorted in ascending order, so no changes are needed.
example_3.py — Empty List
$
Input:
head = []
›
Output:
[]
💡 Note:
An empty linked list remains empty after sorting.
Constraints
- The number of nodes in the list is in the range [0, 5 × 104]
- -105 ≤ Node.val ≤ 105
- Follow up: Can you sort the linked list in O(n log n) time and O(1) memory (i.e. constant space)?
Visualization
Tap to expand
Understanding the Visualization
1
Divide
Split the linked list into two halves using slow/fast pointers
2
Conquer
Recursively sort each half until we have single nodes
3
Merge
Merge two sorted halves back together in sorted order
Key Takeaway
🎯 Key Insight: Merge sort is perfect for linked lists because merging is naturally efficient with pointer manipulation, and we don't need the random access that other O(n log n) algorithms require.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code