Sort Linked List Already Sorted Using Absolute Values - Problem
You're given a singly linked list that has an interesting property: it's already sorted in non-decreasing order by the absolute values of its nodes. However, the actual values might be negative, making the list appear unsorted when considering the real values.
Your task is to sort this linked list by the actual values (not absolute values) while maintaining the non-decreasing order.
For example, if you have a list like
The key insight is that since the list is already sorted by absolute values, negative numbers with larger absolute values need to be moved to the front, while maintaining the relative order of positive numbers.
Your task is to sort this linked list by the actual values (not absolute values) while maintaining the non-decreasing order.
For example, if you have a list like
[-5, -2, 3, 4, -6] which is sorted by absolute values [5, 2, 3, 4, 6], you need to rearrange it to [-6, -5, -2, 3, 4] sorted by actual values.The key insight is that since the list is already sorted by absolute values, negative numbers with larger absolute values need to be moved to the front, while maintaining the relative order of positive numbers.
Input & Output
example_1.py โ Basic Case
$
Input:
head = [-5, -2, 3, 4, -6]
โบ
Output:
[-6, -5, -2, 3, 4]
๐ก Note:
The original list is sorted by absolute values: |5|, |2|, |3|, |4|, |6|. After sorting by actual values, negative numbers come first in descending order of their absolute values, followed by positive numbers.
example_2.py โ Only Positive Values
$
Input:
head = [1, 3, 5, 7, 9]
โบ
Output:
[1, 3, 5, 7, 9]
๐ก Note:
Since all values are positive, the list is already sorted by actual values and remains unchanged.
example_3.py โ Only Negative Values
$
Input:
head = [-1, -3, -5]
โบ
Output:
[-5, -3, -1]
๐ก Note:
All values are negative, so we need to reverse the order since the original was sorted by absolute values (1 < 3 < 5), but for actual values we need -5 < -3 < -1.
Constraints
- The number of nodes in the list is in the range [0, 104]
- -104 โค Node.val โค 104
- The list is sorted in non-decreasing order by absolute values
- You must sort the list in non-decreasing order by actual values
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Original list is sorted by |value|: |-5|=5, |-2|=2, |3|=3, |4|=4, |-6|=6
2
Separate by Sign
Split into negative [-5, -2, -6] and positive [3, 4] sublists
3
Reverse Negatives
Reverse negative list to [-6, -5, -2] for correct ordering
4
Merge Lists
Connect reversed negative list to positive list: [-6, -5, -2, 3, 4]
Key Takeaway
๐ฏ Key Insight: Since the list is sorted by absolute values, we only need to handle the relative positioning of negative numbers (which should be reversed) and positive numbers (which are already correctly ordered).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code