Given an array **arr[] **consisting of **N **integers, denoting N points lying on the X-axis, the task is to find the point which has the least sum of distances from the all other points.

Example:

Input:_ arr[] = {4, 1, 5, 10, 2}_

Output:_ (4, 0)_

Explanation:

Distance of 4 from rest of the elements = |4 – 1| + |4 – 5| + |4 – 10| + |4 – 2| = 12

Distance of 1 from rest of the elements = |1 – 4| + |1 – 5| + |1 – 10| + |1 – 2| = 17

Distance of 5 from rest of the elements = |5 – 1| + |5 – 4| + |5 – 2| + |5 – 10| = 13

Distance of 10 from rest of the elements = |10 – 1| + |10 – 2| + |10 – 5| + |10 – 4| = 28

Distance of 2 from rest of the elements = |2 – 1| + |2 – 4| + |2 – 5| + |2 – 10| = 14

Input:_ arr[] = {3, 5, 7, 10}_

Output:_ 5_

Naive Approach:

The task is to iterate over the array, and for each array element, calculate the sum of its absolute difference with all other array elements. Finally, print the array element with the maximum sum of differences.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **To optimize the above approach, the idea is to find the median of the array. The median of the array will have the least possible total distance from other elements in the array. For an array with even number of elements, there are two possible medians and both will have the same total distance, return the one with the lower index since it is closer to origin.

Follow the below steps to solve the problem:

  • Sort the given array.
  • If **N **is odd, return the **(N + 1 / 2)th **element.
  • Otherwise, return the **(N / 2)th **element.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to find median of the array

**int** findLeastDist(``**int** A[], **int** N)

{

// Sort the given array

sort(A, A + N);

// If number of elements are even

**if** (N % 2 == 0) {

// Return the first median

**return** A[(N - 1) / 2];

}

// Otherwise

**else** {

**return** A[N / 2];

}

}

// Driver Code

**int** main()

{

**int** A[] = { 4, 1, 5, 10, 2 };

**int** N = **sizeof**``(A) / **sizeof**``(A[0]);

cout << "(" << findLeastDist(A, N)

<< ", " << 0 << ")"``;

**return** 0;

}

Output:

(4, 0)

Time Complexity:_ O(Nlog(N))_

Auxiliary Space:_ O(1)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #geometric #mathematical #sorting #geometric-lines #median-finding

Find the point on X-axis from given N points having least Sum of Distances
2.65 GEEK