Rearrange Array Elements Problem Statement

Given an array A containing 'N' integers and an integer m, rearrange the elements of the array such that the differences between the array elements and m are sorted in order.

If multiple elements have the same difference from m, maintain their order from the original array.

Example:

Input:
A = [3, 5, 7, 9, 2, 6], m = 5
Output:
[5, 6, 3, 7, 2, 9]
Explanation:

The differences are: [2, 0, 2, 4, 3, 1]. Reordered array: [5, 6, 3, 7, 2, 9].

Input:

The first line contains a single integer ‘T’ denoting the number of test cases.
The first line of each test case contains two integers, ‘N’ - the number of elements in the array, and ‘m’.
The second line of each test case contains ‘N’ space-separated integers comprising ‘A’.

Output:

For each test case, print space-separated integers representing the elements of the re-arranged array.
Print the output for each test case on a separate line.

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 105
  • 1 <= m <= 105
Note:
You do not need to print anything as it has already been handled. Implement the function to solve the problem.
Be the first one to answer
Add answer anonymously...
Info Edge Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter