CodingNodes / Linked List / Sort List System design Space play · ←→ step · R restart

Problem

You get the head of a linked list of integers. Return the list sorted from smallest to largest, built by re-linking the existing nodes.

A list has no random access, so sorting it in place with indexes is not possible. Merge sort fits well: it only needs to walk the list and re-link nodes.

Constraints

  • 0 ≤ number of nodes ≤ 50000
  • -100000 ≤ Node.val ≤ 100000

Examples: pick one to animate

Solutions

TimeO(n log n) SpaceO(log n)

Time: The list is halved about log n times, and each level of the recursion re-links all n nodes once while merging.

Space: No new nodes are made. The only extra memory is the recursion stack, which is about log n calls deep.

Find the middle with a slow pointer that moves one node while a fast pointer moves two. Cut the list there, sort each half with the same function, then merge the two sorted halves with the usual two-pointer merge. A list of zero or one nodes is already sorted, which ends the recursion.