Skip to content
BytePatterns

Sort a Linked Chain

MediumSorting#divide-and-conquer#fast-slow-pointers~30m

Problem

Given the head of a singly linked list of numbers, return the head of the same nodes relinked into ascending order. Nodes may not be copied into a Python list and sorted there; the answer should relink the existing nodes in O(n log n) time. The list may be empty.

Examples

Input:  4 -> 1 -> 3 -> 1 -> 2
Output: 1 -> 1 -> 2 -> 3 -> 4
Why:    duplicates are kept, only the links change
Input:  -3 -> 8
Output: -3 -> 8
Why:    already in order, so the relinking is a no-op
Input:  empty
Output: empty
Why:    edge case, an empty chain is already sorted

Hints

0 / 3

Stuck on the idea rather than the code? Merge Sort covers it.