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
INPUT4213Unsorted linked listvalues: [4,2,1,3]ALGORITHM1Find MiddleUse slow-fast pointers2Split & SortRecursively sort halves3Merge BackCombine in orderTime: O(n log n)Space: O(log n)RESULT1234[1,2,3,4]Sorted in ascending orderKey Insight:Divide-and-conquer with slow-fast pointers makes linked list sortingefficient by recursively splitting at middle and merging sorted halves.TutorialsPoint - Linked List Sorter | Merge Sort Algorithm
Asked in
Amazon 45 Microsoft 38 Google 32 Apple 25
78.0K Views
High Frequency
~25 min Avg. Time
2.2K 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