Skip to problem
←

Merge Sort for Linked Lists

Hard 0 attempts

Given the head of a singly linked list, sort its nodes in non-decreasing order using merge sort and return the sorted list’s head.

Preserve every value, including duplicates. The input may be empty, in which case return null. You may relink the input nodes. The arrays shown in examples are only a display format; your function receives linked-list nodes, not an array.

Split the list into two halves, sort each half, then merge them. Aim for O(n log n) time without converting the list to an array.

Function contract

Implement mergeSortForLinkedLists(head). The editor converts each displayed array into a singly linked list with val and next properties; [] becomes null.

Output: Return the head of the list sorted in non-decreasing order, preserving every value and duplicate. The runner displays the returned list as an array; null displays as [].

Example 1

Input
head = [4,2,1,3]
Output
[1,2,3,4]

Example 2

Input
head = [-1,5,3,4,0]
Output
[-1,0,3,4,5]
Constraints
  • 0 <= number of nodes <= 5 * 10^4
  • -10^5 <= Node.val <= 10^5

Approach: Split and Merge Linked Lists

Use slow and fast pointers to find the middle, then cut the link before sorting the two halves recursively. Merge the sorted halves by relinking their nodes. The merge is iterative, so a long list does not create a linear-depth call stack. Only the balanced splitting is recursive.

javascript
function mergeSortForLinkedLists(head) {
  if (!head || !head.next) return head;
  let slow = head;
  let fast = head.next;
  while (fast && fast.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  const second = slow.next;
  slow.next = null;
  let left = mergeSortForLinkedLists(head);
  let right = mergeSortForLinkedLists(second);
  const dummy = { next: null };
  let tail = dummy;
  while (left && right) {
    if (left.val <= right.val) {
      tail.next = left;
      left = left.next;
    } else {
      tail.next = right;
      right = right.next;
    }
    tail = tail.next;
  }
  tail.next = left || right;
  return dummy.next;
}

Time Complexity: O(n log n).

Space Complexity: O(log n) auxiliary space for recursive splitting. Existing nodes are reused.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript