Leetcode #147: Insertion Sort List
In this guide, we solve Leetcode #147 Insertion Sort List in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. The steps of the insertion sort algorithm: Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Linked List, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Python Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
dummy = ListNode(head.val, head)
pre, cur = dummy, head
while cur:
if pre.val <= cur.val:
pre, cur = cur, cur.next
continue
p = dummy
while p.next.val <= cur.val:
p = p.next
t = cur.next
cur.next = p.next
p.next = cur
pre.next = t
cur = t
return dummy.next
Complexity
The time complexity is O(n log n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.