Insertion Sort List

Medium

Topics
Linked ListSorting

Given the head of a singly linked list, sort it in ascending order using insertion sort and return the sorted list.

Example 1

before4213null
sorted1234null
Each node is lifted from the input and walked down the already-sorted prefix until it fits. On an array that means shifting elements along; on a linked list it is just a pointer rewire, so a dummy head and a scan from it per node is the whole algorithm.
Linked list values from head to tail.
Input:  head = [4,2,1,3]
Output: [1,2,3,4]

Example 2

before-15340null
sorted-10345null
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

  1. Dummy node before an empty sorted region.
  2. For each node: save its successor, walk the sorted region to find the last node with a smaller value, splice it in there.
  3. 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 -> 4

Complexity

  • 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.next before rewiring. Splicing the node elsewhere overwrites its next and 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 dummy rather than dummy.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.next
SensAI
Beta
Tap the mic to stop voice mode