Insertion Sort List

MediumLinked Listsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the head of a non-empty singly linked list, sort it in **ascending** order using insertion sort and return the head of the sorted list. Insertion sort grows a sorted list one node at a time: take the next node from the unsorted remainder and splice it into its correct position within the sorted part. Equal values may end up in any relative order (they are indistinguishable in the output). Relink the existing nodes rather than copying values into an array; O(n^2) time and O(1) extra space are expected.

Examples

Input: head = [4,2,1,3]
Output: [1,2,3,4]
Nodes are inserted one by one into the growing sorted list.
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Negative values sort like any others.

Constraints

  • 1 <= number of nodes <= 5000
  • -5000 <= Node.val <= 5000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems