![]() |
VOOZH | about |
Given an array arr[] consisting of distinct elements and a number x, arrange array elements 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:
Input: x = 7, arr[] = [10, 5, 3, 9, 2]
Output: [5, 9, 10, 3, 2]
Explanation: abs(7 - 10) = 3, 7 - 5 = 2, 7 - 3 = 4 , abs(7 - 9) = 2 and 7 - 2 = 5,So according to the difference with X, elements are arranged as 5, 9, 10, 3, 2.Input: x = 6, arr[] = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: When sorted on the basis of absolute difference with x the elements will be sorted in the given order.
Table of Content
The idea is to use a self-balancing binary search tree. We traverse the input array and for every element, we find its difference with x and store the difference as key and element as the value in a self-balancing binary search tree. Finally, we traverse the tree and print its inorder traversal which is the required output.
Step-By-Step Approach:
5 9 10 3 2
Note: In C++, self-balancing-binary-search-tree is implemented by set, map, and multimap. We can't use set here as we have key-value pairs (not only keys). We also can't directly use map also as a single key can belong to multiple values and map allows a single value for a key. So we use multimap which stores key-value pairs and can have multiple values for a key.
In C++, we can use stable_sort(), and write a lambda expression for the custom comparator function. This solution is elegant and far easier to understand. The only challenge in writing the lambda expression is to send the value 'x' into the lambda expression to be able to use it inside the expression. This can be achieved either by operator overloading with the help of a class or using a much simpler capture.
Note: C# does not offer a built-in stable sorting algorithm for arrays; the default Array.Sort method is not guaranteed to be stable.
5 9 10 3 2