Insertion Sort List (LeetCode 147): Solution and Explanation

Medium
Linked List
Sorting

Sort a singly linked list with insertion sort. Keep a sorted chain behind a dummy node, take nodes from the input one at a time, walk to the spot where each one belongs and splice it in.

Intuition

Insertion sort on an array shifts elements to open a gap. A linked list does not need to shift anything: once you know which node the new one should follow, two pointer writes put it in place.

So keep two lists. The sorted chain starts empty behind a dummy node, and the rest of the input is the unsorted list. Each round takes the first unsorted node and finds its spot in the sorted chain.

The spot is right after the last sorted node whose value is smaller. Walking a pointer prev from dummy while prev.next is smaller finds it, and the dummy makes inserting at the front look the same as inserting anywhere else.

Approach: Dummy head plus splice

  1. Create dummy as the head of an empty sorted chain and set cur = head.
  2. While cur is not null, save nxt = cur.next, because the splice will overwrite it.
  3. Start prev at dummy and move it forward while prev.next exists and prev.next.val < cur.val.
  4. Splice cur in: cur.next = prev.next, then prev.next = cur.
  5. Set cur = nxt and repeat. When the input is used up, return dummy.next.

Step-by-step example

head = [4,2,1,3]
  1. The sorted chain is empty. cur is 4; prev stays on dummy because dummy.next is null, so the chain becomes 4.
  2. cur is 2. dummy.next is 4, which is not smaller than 2, so prev stays on dummy and 2 goes in front: 2, 4.
  3. cur is 1. dummy.next is 2, not smaller than 1, so 1 goes in front: 1, 2, 4.
  4. cur is 3. prev walks past 1 and 2 because both are smaller, then stops because 4 is not smaller. 3 goes between 2 and 4: 1, 2, 3, 4.
  5. cur is null, so return dummy.next, which is [1,2,3,4].

Code: Python, Java, C++

1class Solution:
2    def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
3        dummy = ListNode(0)
4        cur = head
5        while cur:
6            nxt = cur.next
7            prev = dummy
8            while prev.next and prev.next.val < cur.val:
9                prev = prev.next
10            cur.next = prev.next
11            prev.next = cur
12            cur = nxt
13        return dummy.next
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Each node may scan the whole sorted chain before it is placed, so a reversed input makes about n^2 / 2 comparisons. An already sorted input still scans to the end each time with this simple version.

Space

O(1)

Only the dummy node and a few pointers. Nodes are relinked, never copied.

Other approaches

Remember the last inserted position (time O(n^2), space O(1))

Only reset prev to dummy when cur is smaller than the last sorted node. Inputs that are mostly sorted then take close to O(n), while the worst case stays O(n^2).

Merge sort on the list (time O(n log n), space O(log n))

Split at the middle with slow and fast pointers, sort both halves and merge them. It is the right choice for large lists, but it is not the insertion sort the problem asks for.

Common mistakes

  • Forgetting to save cur.next before the splice. After cur.next = prev.next you can no longer reach the rest of the input.
  • Writing prev.next = cur before cur.next = prev.next. That makes cur point at itself and loses the rest of the sorted chain.
  • Skipping the dummy node and special-casing a new minimum. It works, but it is the most common source of bugs here.
  • Using <= in the scan. It still sorts correctly, but it walks past equal values for no reason and stops being stable.

Frequently asked questions

Why is the comparison strict (<)?

With <, prev stops before the first node that is equal or larger, so a new node goes in front of equal values it meets. Either choice sorts correctly; the strict version does fewer steps when there are many duplicates.

Is swapping values instead of relinking nodes allowed?

It returns the right values, but the problem is about rearranging the list, and in real code nodes often carry more than one field. Relinking nodes is the intended solution.

How is this different from Sort List?

Sort List asks for O(n log n) time, which means merge sort. This problem asks for insertion sort specifically, which is O(n^2) but simple and in place.

Why does the dummy node matter?

Without it, inserting a node smaller than everything needs its own branch that changes the head. With it, the head of the sorted chain is just dummy.next and every insertion uses the same two lines.