Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Merge Sort for Linked List

Medium Acceptance 74.76% Points 30.00

Given a reference to the head of a linked list, the task is to sort the linked list using the Merge Sort algorithm.

Note: When splitting the linked list, the extra node should be included in the first half if the number of nodes is odd.

Examples
Example 1

Example 1

Input: LinkedList: 15 -> 10 -> 5 -> 20 -> 3

Output: 3 -> 5 -> 10 -> 15 -> 20

Explanation: The Merge Sort algorithm sorts the nodes in ascending order, resulting in 3 -> 5 -> 10 -> 15 -> 20.

Example 2

Example 2

Input: LinkedList: 9 -> 7 -> 8 -> 6 -> 5

Output: 5 -> 6 -> 7 -> 8 -> 9

Explanation: The linked list is split into smaller parts, sorted, and merged to form the sorted list 5 -> 6 -> 7 -> 8 -> 9.

Hints
Hint 1
Expected Time Complexity: O(n*log(n))
Hint 2
Expected Space Complexity: O(n)
Constraints
  • 1 <= number of nodes <= 10^5
  • 0 <= node->data <= 10^6
Companies
Amazon Microsoft Adobe Paytm
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions