LeetCode #147 Medium

Insertion Sort List

Insertion Sort List is LeetCode 147 (Medium). Given the head of a singly linked list, sort it in ascending order using insertion sort and return the new head.

  • Insertion sort keeps a sorted part at the front and moves each following item into its correct place in that part.
  • On a linked list, moving an item means changing next pointers, not shifting values.
  • The list holds 1 to 5000 nodes, so the O(n²) worst case is fine here.
Constraints
  • The number of nodes in the list is in the range [1, 5000]
  • -5000 <= Node.val <= 5000
linked-listsorting
Open on LeetCode ↗
02

Intuition

Split the list in two: a sorted front part and the nodes still waiting behind it. Look at the first waiting node, cur.

  • No move needed: if cur is at least as large as the last sorted node, it is already in place. The sorted part just grows by one.
  • Move it: otherwise, unhook cur and walk the sorted part from the start until the next node is larger than cur, then hook it in there.

A dummy node before the head makes "insert at the very front" the same as any other insert, so the head needs no special case. The dummy's next is the answer.

How to spot this pattern

The problem names the algorithm. The linked-list part is the work: you cannot step backward, so each search for a slot starts from the front.

03

Approach

Try it first

Before reading on, sort 4 → 2 → 1 → 3 on paper. For each node, write which pointer you change and which node you start searching from. How many next pointers does one move change?

1

Put a dummy node in front

Create dummy with dummy.next = head, and let last = head be the end of the sorted part. With the dummy, a node that belongs first is placed after dummy like any other.

2

Leave nodes that are already in order

Take cur = last.next. If last.val <= cur.val, cur is not smaller than anything sorted, so just set last = cur. This check makes an already sorted list cost only one pass.

3

Find the slot from the front

Otherwise start prev at dummy and step while prev.next.val <= cur.val. The walk stops before the first node larger than cur, so equal values keep their original order. It always stops inside the sorted part, because last is larger than cur.

4

Relink three pointers

Unhook cur with last.next = cur.next, then hook it in with cur.next = prev.next and prev.next = cur. Do it in this order, so the rest of the list is never cut off.

5

Continue from the end of the sorted part

The next node to place is always last.next, whether cur moved or not. When it is None, every node is sorted; return dummy.next.

04

Code in Python, C++ and Java

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
▶6 dummy = ListNode(0, head)
▶7 last = head
▶8 while last.next:
▶9 cur = last.next
▶10 if last.val <= cur.val:
▶11 last = cur
▶12 continue
▶13 prev = dummy
▶14 while prev.next.val <= cur.val:
▶15 prev = prev.next
▶16 last.next = cur.next
▶17 cur.next = prev.next
▶18 prev.next = cur
▶19 return dummy.next
sortedwaitingdummy4213lastthe first node, 4, is a sorted part on its own
last4
A dummy node sits in front of the head so that a node can be placed first without a special case. One node on its own is already sorted, so the sorted part starts as just 4.
sortedwaitingdummy4213lastcur2 is below 4 → search from the front
cur2
last4
2 is smaller than the last sorted value, 4, so it belongs somewhere earlier. A singly linked list cannot step backward, so the search starts at the dummy.
sortedwaitingdummy4213prevlastcur4 is above 2 → slot is after dummy
prevdummy
prev.next4
4 is the first sorted node larger than 2, so 2 goes right before it, after the dummy, which makes it the new first node.
sortedwaitingdummy2413prevlastrelink: 2 now sits before 4
list2 → 4 → 1 → 3
Three pointers change: 4 skips over 2, 2 points to 4, and the dummy points to 2. 4 is still the end of the sorted part, so the next node to place is the one after it.
sortedwaitingdummy2413lastcur1 is below 4 → search from the front
cur1
last4
1 is smaller than the last sorted value, 4, so it belongs somewhere earlier. A singly linked list cannot step backward, so the search starts at the dummy.
sortedwaitingdummy2413prevlastcur2 is above 1 → slot is after dummy
prevdummy
prev.next2
2 is the first sorted node larger than 1, so 1 goes right before it, after the dummy, which makes it the new first node.
sortedwaitingdummy1243prevlastrelink: 1 now sits before 2
list1 → 2 → 4 → 3
Three pointers change: 4 skips over 1, 1 points to 2, and the dummy points to 1. 4 is still the end of the sorted part, so the next node to place is the one after it.
sortedwaitingdummy1243lastcur3 is below 4 → search from the front
cur3
last4
3 is smaller than the last sorted value, 4, so it belongs somewhere earlier. A singly linked list cannot step backward, so the search starts at the dummy.
sortedwaitingdummy1243prevlastcur1 is not above 3 → step past it
prevdummy
prev.next1
1 is not larger than 3, so 3 goes somewhere after it. Move prev forward.
sortedwaitingdummy1243prevlastcur2 is not above 3 → step past it
prev1
prev.next2
2 is not larger than 3, so 3 goes somewhere after it. Move prev forward.
sortedwaitingdummy1243prevlastcur4 is above 3 → slot is after 2
prev2
prev.next4
4 is the first sorted node larger than 3, so 3 goes right before it, after 2.
sorteddummy1234prevlastrelink: 3 now sits before 4
list1 → 2 → 3 → 4
Three pointers change: 4 skips over 3, 3 points to 4, and 2 points to 3. 4 is still the end of the sorted part, so the next node to place is the one after it.
sorteddummy1234sorted: return the node after dummy
answer1 → 2 → 3 → 4
No node waits behind the sorted part. The head may have moved, so the answer is whatever the dummy points to: 1 → 2 → 3 → 4.
05

Common pitfalls

Hooking the node in before unhooking it

✗ Wrong
cur.next = prev.next
prev.next = cur
last.next = cur.next
✓ Right
last.next = cur.next
cur.next = prev.next
prev.next = cur

After the first two lines cur.next points into the sorted part, so the third line makes last point back into the list and cuts off everything after cur. On 2 → 1 → 3, the node holding 2 ends up pointing to itself: 3 is lost and the loop never ends.

Returning the old head

✗ Wrong
return head
✓ Right
return dummy.next

The first node can move. On 4 → 2 → 1 → 3, head is still the node holding 4, which is now last, so returning it gives just 4.

06

Edge cases

Already sorted, e.g. 1 → 2 → 3

Every node passes the tail check, so no search runs and the sort takes O(n).

Sorted in reverse, e.g. 3 → 2 → 1

Every node belongs at the front, so each search stops at once at dummy. Reverse order is not the slow case here; the slow case is when each node belongs near the end of the sorted part.

07

Complexity

Time
O(n²)
Space
O(1)
Each node may walk the whole sorted part to find its slot, so up to about n²/2 steps. Only pointers move; no new nodes are made. The tail check brings sorted input down to O(n).
08

Insertion Sort List FAQ

Why not use merge sort?

Merge sort sorts a linked list in O(n log n) and is the right tool when only speed matters; that is Sort List (LeetCode 148). This problem asks for insertion sort specifically, and with 5000 nodes the quadratic version is fast enough.

Is it all right to copy the values into an array, sort, and write them back?

It returns a sorted list, but it is not insertion sort and uses O(n) extra memory. Interviewers asking this problem want to see the pointer work, so moving nodes is the expected answer.

Can the search start at the last insert spot instead of the front?

Yes, if the node to place is larger than the previous insert spot, the walk can start there, and that saves steps on nearly sorted input. It does not change the O(n²) worst case, and a singly linked list still forces a restart from dummy for smaller values.