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
Sort Linked List INPUT Linked List Structure: 4 2 1 3 NULL Input: head = [4, 2, 1, 3] Unsorted linked list No random access Sequential traversal only Requirements: Time: O(n log n) Space: O(log n) ALGORITHM STEPS (Merge Sort) 1 Find Middle Use slow/fast pointers slow=head, fast=head 2 Split List Divide at middle point [4,2] [1,3] 3 Recursive Sort Sort both halves [2,4] [1,3] 4 Merge Sorted Combine in order Compare heads, link smaller 1 --> 2 --> 3 --> 4 FINAL RESULT Sorted Linked List: 1 2 3 4 NULL Output: [1, 2, 3, 4] OK - Sorted! Ascending order verified 1 < 2 < 3 < 4 O(n log n) achieved Key Insight: Merge Sort is ideal for linked lists because it only requires sequential access. The slow/fast pointer technique finds the middle in O(n) without random access. Unlike arrays, merging linked lists needs O(1) extra space - just pointer manipulation! TutorialsPoint - Sort List | Merge Sort (Optimal Approach)
Asked in
Amazon 45 Microsoft 38 Meta 32 Google 28
89.0K Views
High Frequency
~25 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen