Sort Linked List Already Sorted Using Absolute Values

MediumLinked Listin-place reversal

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

You are given the head of a linked list that is sorted in non-decreasing order of the **absolute values** of its nodes. Rearrange the list so that it is sorted in non-decreasing order of the **actual** values, and return the new head. A general sort costs O(n log n). Solve it in O(n) time with O(1) extra space by exploiting the existing order.

Examples

Input: head = [1,-2,-3,4,-5]
Output: [-5,-3,-2,1,4]
The negatives -2, -3, -5 appear in increasing magnitude, so in actual order they go in reverse: -5, -3, -2. Then 1 and 4 follow.
Input: head = [0,-1,1,-1]
Output: [-1,-1,0,1]
The absolute values 0, 1, 1, 1 are non-decreasing; sorting by real value moves both -1 nodes to the front.
Input: head = [-7]
Output: [-7]
A single node is already sorted.

Constraints

  • 1 <= number of nodes <= 10^5
  • -5000 <= Node.val <= 5000
  • The list is sorted by absolute value in non-decreasing order

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 in-place reversal problems