Insertion Sort List (LeetCode 147): Solution and Explanation
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
- Create
dummyas the head of an empty sorted chain and setcur = head. - While
curis not null, savenxt = cur.next, because the splice will overwrite it. - Start
prevatdummyand move it forward whileprev.nextexists andprev.next.val < cur.val. - Splice
curin:cur.next = prev.next, thenprev.next = cur. - Set
cur = nxtand repeat. When the input is used up, returndummy.next.
Step-by-step example
head = [4,2,1,3]
- The sorted chain is empty. cur is 4; prev stays on dummy because dummy.next is null, so the chain becomes 4.
- 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.
- cur is 1. dummy.next is 2, not smaller than 1, so 1 goes in front: 1, 2, 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.
- 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.next1class Solution {
2 public ListNode insertionSortList(ListNode head) {
3 ListNode dummy = new ListNode(0);
4 ListNode cur = head;
5 while (cur != null) {
6 ListNode nxt = cur.next;
7 ListNode prev = dummy;
8 while (prev.next != null && prev.next.val < cur.val) {
9 prev = prev.next;
10 }
11 cur.next = prev.next;
12 prev.next = cur;
13 cur = nxt;
14 }
15 return dummy.next;
16 }
17}1class Solution {
2public:
3 ListNode* insertionSortList(ListNode* head) {
4 ListNode dummy(0);
5 ListNode* cur = head;
6 while (cur) {
7 ListNode* nxt = cur->next;
8 ListNode* prev = &dummy;
9 while (prev->next && prev->next->val < cur->val) {
10 prev = prev->next;
11 }
12 cur->next = prev->next;
13 prev->next = cur;
14 cur = nxt;
15 }
16 return dummy.next;
17 }
18};Time and space complexity
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.
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.nextyou can no longer reach the rest of the input. - Writing
prev.next = curbeforecur.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.