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
Insertion Sort List Problem OverviewTransform unsorted linked list into sorted orderInput List:4213⬇ Insertion Sort Algorithm ⬇Each node inserted at correct position in sorted portionSorted Result:1234
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
Asked in
Microsoft 35 Apple 28 Facebook 22 Amazon 18
89.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen