17. Sort by Absolute Difference
β GFG solution to the Sort by Absolute Difference problem: rearrange array elements based on their absolute difference from a target value using stable sorting technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a number x
and array arr[]
. Your task is to rearrange the elements of the array according to the absolute difference with x
, i.e., an element having minimum difference comes first, and so on.
Note: If two or more elements are at equal distances arrange them in the same sequence as in the given array.
π Examples
Example 1
Input: x = 7, arr[] = [10, 5, 3, 9, 2]
Output: [5, 9, 10, 3, 2]
Explanation: Sorting the numbers according to the absolute difference with 7:
- |5-7| = 2 (closest)
- |9-7| = 2 (same distance, maintain original order)
- |10-7| = 3
- |3-7| = 4
- |2-7| = 5 (farthest)
Example 2
Input: x = 6, arr[] = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: Sorting the numbers according to the absolute difference with 6:
- |5-6| = 1 (closest)
- |4-6| = 2
- |3-6| = 3
- |2-6| = 4
- |1-6| = 5 (farthest)
π Constraints
$1 \le x \le 10^5$
$1 \le \text{arr.size()} \le 10^5$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses Stable Sort with a Custom Comparator to maintain the original relative order of elements with equal absolute differences:
Stable Sort with Lambda Comparator
Custom Comparator:
Define a lambda function that compares two elements based on their absolute difference from
x
.For elements
a
andb
, compare|a - x|
with|b - x|
.
Stable Sorting:
Use
stable_sort()
instead of regularsort()
to preserve the original order of elements with equal distances.This ensures that if
|a - x| == |b - x|
, thena
andb
maintain their relative positions from the original array.
In-Place Rearrangement:
The sorting is performed directly on the input array without requiring additional space for the result.
Algorithm Flow:
Calculate absolute difference for each element with respect to
x
.Sort elements in ascending order of their absolute differences.
Elements with smaller differences appear first in the final arrangement.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the size of the array. This is due to the stable sorting operation which has a time complexity of O(n log n).
Expected Auxiliary Space Complexity: O(1), as we perform the sorting operation in-place without using any additional data structures proportional to the input size.
π§βπ» Code (C++)
class Solution {
public:
void rearrange(vector<int> &arr, int x) {
stable_sort(arr.begin(), arr.end(), [x](int a, int b) {
return abs(a - x) < abs(b - x);
});
}
};
β Code (Java)
class Solution {
public void rearrange(int[] arr, int x) {
Integer[] indices = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) indices[i] = i;
Arrays.sort(indices, (a, b) -> Integer.compare(Math.abs(arr[a] - x), Math.abs(arr[b] - x)));
int[] temp = new int[arr.length];
for (int i = 0; i < arr.length; i++) temp[i] = arr[indices[i]];
System.arraycopy(temp, 0, arr, 0, arr.length);
}
}
π Code (Python)
class Solution:
def rearrange(self, arr, x):
arr.sort(key=lambda val: abs(val - x))
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated