Linked List Sorter - Problem
Given the head of a singly linked list, sort it using merge sort algorithm and return the sorted list's head.
You must implement the complete merge sort algorithm for linked lists, which involves:
- Finding the middle of the linked list
- Splitting the list into two halves
- Merging two sorted linked lists
The algorithm should work in-place and maintain O(n log n) time complexity.
Input & Output
Example 1 — Basic Unsorted List
$
Input:
head = [4,2,1,3]
›
Output:
[1,2,3,4]
💡 Note:
The merge sort algorithm splits the list at middle (between 2 and 1), recursively sorts both halves [4,2]→[2,4] and [1,3]→[1,3], then merges them back: [1,2,3,4]
Example 2 — Already Sorted
$
Input:
head = [1,2,3,4,5]
›
Output:
[1,2,3,4,5]
💡 Note:
Even though the list is already sorted, merge sort still works by splitting and merging, but no reordering occurs during the merge steps
Example 3 — Single Element
$
Input:
head = [42]
›
Output:
[42]
💡 Note:
Base case: a single node is already sorted, so it returns immediately without any splitting or merging
Constraints
- The number of nodes in the list is in the range [0, 5 × 104]
- -105 ≤ Node.val ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code