TRT
Sign in
mediumCoreLeetCode#insertion sort#dummy head

Insertion sort list

Sort a singly linked list with insertion sort, splicing each node into a growing sorted list behind a dummy head.

The Runtime Theory Team1 min read
Taught inInsertion and selection sortPro — members onlyThe two simplest sorts both take O(n²) steps on scrambled data, but they behave very differently: insertion sort is fast on nearly sorted input and is used inside every major library sort.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inhead = [4, 2, 1, 3]

out[1, 2, 3, 4]

inhead = [-1, 5, 3, 4, 0]

out[-1, 0, 3, 4, 5]

inhead = [1]

out[1]

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

  1. Build the sorted list behind a dummy head. Take nodes from the input one at a time.
  2. 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.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save