Sort by Distance From Zero
Return a new list with the items of nums ordered by their absolute value, smallest first. When two items have the same absolute value but different signs, the negative one comes first, so -3 goes before 3. Equal items cannot be told apart, so their order among themselves does not matter.
Do not change nums. An empty list gives an empty list.
Example 1
nums [3,-1,-3,2,0]
returns [0,-1,2,-3,3]
The absolute values are 0, 1, 2, 3, 3; the two 3s tie and the negative one goes first.
Example 2
nums [5,-5,5]
returns [-5,5,5]
-5 goes before the two 5s.
Constraints
0 <= len(nums) <= 100-1000 <= nums[i] <= 1000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Sorting and searching problems
- Sortable With One SwapEasy
- Sorting the SentenceEasy
- Find in a Mountain ListMedium
- Find in a Rotated ListMedium
- H-IndexMedium
- K Closest ValuesMedium
- Kth Smallest Pair SumMedium
- Least Truck CapacityMedium