1588. Absolute to True Order

Medium3.5 points estimatedLinked ListTwo PointersSorting

A thermometer log was recorded in order of how far each reading is from zero, so the list head is sorted non-decreasing by absolute value, with negative and positive readings mixed together. Return the same nodes arranged in non-decreasing order of their actual value. Do not call a general sort: the non-negative nodes already appear in correct order, and the negative ones appear in reverse order of their absolute value, so detaching each negative node and pushing it onto the front of a growing chain finishes the job. Return null for an empty list. O(n) time and O(1) extra space.

Example 1

Input:
head = [0,-1,2,-3,4]
Output:
[-3,-1,0,2,4]
Explanation:

Negatives -1 and -3 are pushed to the front, the last one first: -3, -1, 0, 2, 4.

Example 2

Input:
head = [1,-1,1,-2]
Output:
[-2,-1,1,1]
Explanation:

Sorted by value this is -2, -1, 1, 1.

Example 3

Input:
head = [2,3,5]
Output:
[2,3,5]
Explanation:

There are no negatives, so the list is already in true order.

Constraints

0 ≤ length ≤ 1000

-109 ≤ val ≤ 109

The list is sorted non-decreasing by |val|.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…