Skip to problem
←

Sort List

Medium 0 attempts

Given the head of a singly linked list, rearrange its nodes into nondecreasing order and return the new head.

Reuse every original node exactly once. Change next links as needed, but do not overwrite values or return replacement nodes. Equal-valued nodes may appear in either relative order. An empty list remains empty.

Target O(n log n) time.

Function contract

Implement sortList(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head of the sorted list, reusing every original node exactly once without changing node values. A null head is displayed as [].

Example 1

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

Example 2

Input
head = []
Output
[]
Constraints
  • 0 to 5 * 10^4 nodes
  • -10^5 <= Node.val <= 10^5
Follow-up
  • Can you achieve O(n log n) time with O(1) auxiliary space?

Bottom-Up Merge Sort

Merge adjacent sorted runs of length 1, then 2, then 4, doubling until the run length covers the list. Cut each pair of runs, merge by relinking their original nodes, and attach the merged run to the output of this pass.

The iterative approach avoids the O(log n) call stack required by recursive merge sort. A single dummy node anchors the output and never becomes part of the returned list.

javascript
function sortList(head) {
  let length = 0;
  for (let node = head; node; node = node.next) length++;
  const dummy = {next: head};

  function cut(start, size) {
    if (!start) return null;
    for (let i = 1; i < size && start.next; i++) start = start.next;
    const rest = start.next;
    start.next = null;
    return rest;
  }

  for (let size = 1; size < length; size *= 2) {
    let current = dummy.next;
    let tail = dummy;
    while (current) {
      let left = current;
      let right = cut(left, size);
      current = cut(right, size);
      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;
      while (tail.next) tail = tail.next;
    }
  }
  return dummy.next;
}

Time: O(n log n). Each pass traverses O(n) nodes, and there are O(log n) passes.

Auxiliary space: O(1). Only a fixed number of pointers and one dummy node are used; all output nodes come from the input.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript