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 INPUT Unsorted Linked List: 4 2 1 3 head head = [4, 2, 1, 3] 4 nodes, unsorted Each node contains: ListNode { val, next } ALGORITHM STEPS 1 Create Dummy Node Dummy head for sorted list 2 Track Last Sorted Optimize: skip if ordered 3 Find Insert Position Search from dummy head 4 Insert Node Relink pointers Iteration Example: sorted: [] + 4 --> [4] sorted: [4] + 2 --> [2,4] sorted: [2,4] + 1 --> [1,2,4] sorted: [1,2,4] + 3 --> [1,2,3,4] OK - All nodes sorted! FINAL RESULT Sorted Linked List: 1 2 3 4 head Output: [1, 2, 3, 4] Ascending order - OK Complexity Analysis: Time: O(n^2) worst case Space: O(1) in-place Optimized: Skip if already sorted Verification: 1 < 2 < 3 < 4 List is sorted - OK Key Insight: The optimized insertion sort tracks the last sorted node. If the current node is already greater than the last sorted, we simply extend the sorted portion without searching from the beginning. This reduces comparisons for nearly-sorted lists from O(n^2) to O(n). TutorialsPoint - Insertion Sort List | Optimized Insertion Sort Approach
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