Problem Description
Given the head of a singly linked list that is sorted in non-decreasing order based on the absolute values of its nodes, return the list sorted in non-decreasing order according to the actual values of its nodes.
Key Insights
- The original list is ordered by the absolute value, which means negative values may be in reverse order relative to their actual value.
- The list can essentially be split into two sorted parts: one with negative numbers (in descending order) and one with non-negative numbers (in ascending order).
- Reverse the negative part to obtain its correct ascending order, and then merge the two sorted sub-lists using a two-pointer technique.
- The merging process is analogous to merging two sorted arrays.
Space and Time Complexity
Time Complexity: O(n) – each node is processed a constant number of times. Space Complexity: O(1) – no additional data structures are used aside from pointers.
Solution
We approach the problem by first partitioning the list into two parts:
- The negative sub-list (which is in descending order with respect to actual values).
- The non-negative sub-list (which is already in ascending order).
Next, we reverse the negative sub-list so that it becomes sorted in non-decreasing order. Finally, we merge the two sorted sub-lists into one fully sorted list. This merging can be efficiently done using the two-pointer technique, similar to the merge step in merge sort.
The key trick is to leverage the properties of the input list: knowing that the list is already “almost sorted” by absolute value allows us to complete the task in linear time without having to perform a full sort from scratch.