Insertion Sort List
Medium
Topics
Given the head of a singly linked list, sort it in ascending order using insertion sort and return the sorted list.
Example 1
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Constraints
- 1 <= number of nodes <= 5000
- -5000 <= Node.val <= 5000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Insertion sort on a linked list is in some ways more natural than on an array: inserting into the middle is a pointer rewrite rather than a shift of every later element. What the list lacks is backward traversal, so the search for the insertion point must start from the front each time.
A dummy head is what makes it uniform. Build the sorted portion behind a dummy node, so inserting before the current smallest needs no special case — the dummy is always a valid predecessor.
The detail that catches people: capture current.next before rewiring, because the rewiring destroys it.
Worth saying that O(n^2) is inherent to insertion sort, not to the list. Merge sort on a linked list is O(n log n) and O(1) space — no auxiliary array needed, since merging two lists is pointer surgery — and that is the answer if asked to sort a list efficiently.
Approach
- Dummy node before an empty sorted region.
- For each node: save its successor, walk the sorted region to find the last node with a smaller value, splice it in there.
- Continue from the saved successor.
Dry Run
4 -> 2 -> 1 -> 3
take 4: sorted region empty dummy -> 4
take 2: 2 < 4, insert at front dummy -> 2 -> 4
take 1: 1 < 2, insert at front dummy -> 1 -> 2 -> 4
take 3: walk past 1 and 2, stop before 4
dummy -> 1 -> 2 -> 3 -> 4
answer 1 -> 2 -> 3 -> 4Complexity
- Time — O(n^2): each insertion may scan the whole sorted prefix. On already-sorted input the scan runs to the end every time, which is the worst case rather than the best — the opposite of array insertion sort with a backward scan.
- Space — O(1): the dummy and a few pointers. Nothing is copied, which is the advantage over the array version.
Common Pitfalls
- Not saving
current.nextbefore rewiring. Splicing the node elsewhere overwrites itsnextand the traversal is lost. - Omitting the dummy and special-casing insertion at the head, which is more code and easy to get wrong.
- Comparing with
<=instead of<when walking the sorted prefix. Either is correct here, but<keeps equal elements in their original relative order, which is what makes the sort stable. - Forgetting to terminate the last node's
next, leaving a cycle. - Returning
dummyrather thandummy.next.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def insertionSortList(self, head):
dummy = ListNode(0)
cur = head
while cur:
nxt = cur.next
prev = dummy
while prev.next and prev.next.val < cur.val:
prev = prev.next
cur.next = prev.next
prev.next = cur
cur = nxt
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode cur = head;
while (cur != null) {
ListNode nxt = cur.next;
ListNode prev = dummy;
while (prev.next != null && prev.next.val < cur.val) prev = prev.next;
cur.next = prev.next;
prev.next = cur;
cur = nxt;
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* insertionSortList(ListNode* head) {
ListNode dummy(0);
ListNode* cur = head;
while (cur) {
ListNode* nxt = cur->next;
ListNode* prev = &dummy;
while (prev->next && prev->next->val < cur->val) prev = prev->next;
cur->next = prev->next;
prev->next = cur;
cur = nxt;
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {ListNode}
*/ var insertionSortList = function(head) {
const dummy = new ListNode(0);
let cur = head;
while (cur) {
const nxt = cur.next;
let prev = dummy;
while (prev.next && prev.next.val < cur.val) prev = prev.next;
cur.next = prev.next;
prev.next = cur;
cur = nxt;
}
return dummy.next;
};