Insertion Sort List

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. Insertion sort removes one element from the input in each iteration, finds the place it belongs within the sorted part, and inserts it there, until no input elements remain.

30:00

Insertion Sort List
medium
Free written solution
Topics
Companies

Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. Insertion sort removes one element from the input in each iteration, finds the place it belongs within the sorted part, and inserts it there, until no input elements remain.

Example 1:
Input: {"head":[4,2,1,3]}
Output: [1,2,3,4]
Constraints:
  • The number of nodes in the list is in the range [1,5000][1, 5000].

  • −5000≤Node.val≤5000-5000 \leq \text{Node.val} \leq 5000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[4,2,1,3]}

The list has 4 nodes. Insertion sort grows a sorted chain behind a dummy node, taking one node at a time from the unsorted list and splicing it into place.

placed 0 / 4comparisons 0
sorted chainunsortednullnulldummy4213cur

Sorted chain so far

[]

Variables
VariableValue
cur4
sorted0
DepthFunction Call
Stack empty
0/35