Sort List

Medium#148merge sort

You get the head of a singly linked list of numbers. Sort it in increasing order and return the new head, ideally in O(n log n) time. Our list: 8 → 3 → 5 → 1 — the answer is 1 → 3 → 5 → 8.

input
head: the head of a linked list, maybe empty.
returns
The head of the list sorted in non-decreasing order.
constraints
  • 0 ≤ nodes ≤ 1000
  • −10⁵ ≤ Node.val ≤ 10⁵
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
function sortList(head) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.