Insertion Sort List - Problem
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
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there
- It repeats until no input elements remain
The algorithm maintains a sorted portion at the beginning and processes remaining elements one by one, inserting each into its correct position within the sorted portion.
Input & Output
Example 1 — Basic Unsorted List
$
Input:
head = [4,2,1,3]
›
Output:
[1,2,3,4]
💡 Note:
The insertion sort processes each node: first 4 becomes sorted portion [4], then insert 2 to get [2,4], then insert 1 to get [1,2,4], finally insert 3 to get [1,2,3,4]
Example 2 — Already Sorted
$
Input:
head = [1,2,3,4]
›
Output:
[1,2,3,4]
💡 Note:
List is already sorted, so each node gets inserted at the end of the sorted portion, maintaining the same order
Example 3 — Single Node
$
Input:
head = [1]
›
Output:
[1]
💡 Note:
Single node is already sorted by definition
Constraints
- The number of nodes in the list is in the range [1, 5000]
- -5000 ≤ Node.val ≤ 5000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Unsorted linked list [4,2,1,3]
2
Process
Apply insertion sort by inserting each node at correct position
3
Output
Sorted linked list [1,2,3,4]
Key Takeaway
🎯 Key Insight: Maintain sorted portion and insert each remaining node at its correct position using pointer manipulation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code