Given the head of a singly linked list, sort it using insertion sort and return the new head.
Before you code
In an array, insertion sort shifts elements to open a gap. In a list there is nothing to shift: you unlink the node and splice it in after the right predecessor. Finding that predecessor is the part that costs O(n).
Hints
- Build the sorted list behind a dummy head. Take nodes from the input one at a time.
- For each node, walk the sorted list from the dummy to find the last node whose value is smaller, and splice the new node after it.
- Optimization: if the node is not smaller than the last node you inserted, start the search from there instead of the dummy. On nearly sorted input this makes the sort close to O(n).
Production & complexity notes
When solving Insertion sort list on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Insertion and selection sort to reinforce the underlying pattern.
What it practices
Insertion sort's invariant and its adaptive behavior, from Insertion and selection sort.