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
π 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
aandb, 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|, thenaandbmaintain 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++)
β Code (Java)
π Code (Python)
π§ 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