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

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 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, 0)
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.Â
Below are the steps to implement the above approach:
- Â Initialize the minimum sum of distances with infinity.
- Â Initialize the index of the element with minimum sum of distances as -1.
- Â Iterate over each point in the array.
- Â For the current point, calculate the sum of distances from all other points in the array.
- Â If the sum of distances for the current point is less than the minimum sum of distances, update the minimum sum and the index of the point with the minimum sum.
- Â Return the index of the point with minimum sum of distances.
- Â Print the point with the minimum sum of distances as (point, 0).
Below is the code to implement the above approach:
C++
// C++ implementation of the given approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the point with the least sum of// distances from all other pointsint leastSumOfDistances(int arr[], int n) {    // Initialize the minimum sum of distances with infinity    int minSum = INT_MAX;Â
    // Initialize the index of the element with minimum sum    // of distances as -1    int idx = -1;Â
    // Iterate over each point    for (int i = 0; i < n; i++) {Â
        // Initialize the sum of distances for the current        // point to zero        int sum = 0;Â
        // Calculate the sum of distances of the current        // point from all other points        for (int j = 0; j < n; j++) {            sum += abs(arr[j] - arr[i]);        }Â
        // If the sum of distances for the current point is        // less than the minimum sum of distances, update        // the minimum sum and the index of the point with        // minimum sum        if (sum < minSum) {            minSum = sum;            idx = i;        }    }Â
    // Return the index of the point with minimum sum of    // distances    return idx;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 4, 1, 5, 10, 2 };Â Â Â Â int n = sizeof(arr) / sizeof(int);Â
    // Function call to find the point with the least sum of    // distances from all other points    int idx = leastSumOfDistances(arr, n);Â
    // Printing the result    cout << "("         << arr[idx] << ", " << 0 << ")";Â
    return 0;} |
Java
// Java implementation of the given approachÂ
import java.util.*;Â
public class GFG {    // Function to find the point with the least sum of    // distances from all other points    public static int leastSumOfDistances(int[] arr, int n)    {        // Initialize the minimum sum of distances with        // infinity        int minSum = Integer.MAX_VALUE;Â
        // Initialize the index of the element with minimum        // sum of distances as -1        int idx = -1;Â
        // Iterate over each point        for (int i = 0; i < n; i++) {Â
            // Initialize the sum of distances for the            // current point to zero            int sum = 0;Â
            // Calculate the sum of distances of the current            // point from all other points            for (int j = 0; j < n; j++) {                sum += Math.abs(arr[j] - arr[i]);            }Â
            // If the sum of distances for the current point            // is less than the minimum sum of distances,            // update the minimum sum and the index of the            // point with minimum sum            if (sum < minSum) {                minSum = sum;                idx = i;            }        }Â
        // Return the index of the point with minimum sum of        // distances        return idx;    }Â
    // Driver code    public static void main(String[] args)    {        int[] arr = { 4, 1, 5, 10, 2 };        int n = arr.length;Â
        // Function call to find the point with the least        // sum of distances from all other points        int idx = leastSumOfDistances(arr, n);Â
        // Printing the result        System.out.print("(" + arr[idx] + ", " + 0 + ")");    }} |
Python3
# Python3 implementation of the given approachÂ
# Function to find the point with the least sum of# distances from all other pointsdef leastSumOfDistances(arr, n):    # Initialize the minimum sum of distances with infinity    minSum = float('inf')Â
    # Initialize the index of the element with minimum sum    # of distances as -1    idx = -1Â
    # Iterate over each point    for i in range(n):        # Initialize the sum of distances for the current        # point to zero        sum = 0Â
        # Calculate the sum of distances of the current        # point from all other points        for j in range(n):            sum += abs(arr[j] - arr[i])Â
        # If the sum of distances for the current point is        # less than the minimum sum of distances, update        # the minimum sum and the index of the point with        # minimum sum        if sum < minSum:            minSum = sum            idx = iÂ
    # Return the index of the point with minimum sum of    # distances    return idxÂ
# Driver codearr = [4, 1, 5, 10, 2]n = len(arr)Â
# Function call to find the point with the least sum of# distances from all other pointsidx = leastSumOfDistances(arr, n)Â
# Printing the resultprint("({}, {})".format(arr[idx], 0)) |
C#
// C# implementation of the given approachÂ
using System;Â
class Program{    // Function to find the point with the least sum of distances from all other points    static int LeastSumOfDistances(int[] arr, int n)    {        // Initialize the minimum sum of distances with infinity        int minSum = int.MaxValue;Â
        // Initialize the index of the element with minimum sum of distances as -1        int idx = -1;Â
        // Iterate over each point        for (int i = 0; i < n; i++)        {            // Initialize the sum of distances for the current point to zero            int sum = 0;Â
            // Calculate the sum of distances of the current point from all other points            for (int j = 0; j < n; j++)            {                sum += Math.Abs(arr[j] - arr[i]);            }Â
            // If the sum of distances for the current point is less than the minimum sum of distances,            // update the minimum sum and the index of the point with minimum sum            if (sum < minSum)            {                minSum = sum;                idx = i;            }        }Â
        // Return the index of the point with minimum sum of distances        return idx;    }Â
    static void Main()    {        int[] arr = { 4, 1, 5, 10, 2 };        int n = arr.Length;Â
        // Function call to find the point with the least sum of distances from all other points        int idx = LeastSumOfDistances(arr, n);Â
        // Printing the result        Console.WriteLine($"({arr[idx]}, 0)");    }} |
(4, 0)
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 an 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 arrayint 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 Codeint main(){Â
    int A[] = { 4, 1, 5, 10, 2 };    int N = sizeof(A) / sizeof(A[0]);    cout << "(" << findLeastDist(A, N)         << ", " << 0 << ")";Â
    return 0;} |
Java
// Java program to implement// the above approachimport java.util.*;Â
class GFG{Â
// Function to find median of the arraystatic int findLeastDist(int A[], int N){         // Sort the given array    Arrays.sort(A);Â
    // 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 Codepublic static void main(String[] args){Â Â Â Â int A[] = { 4, 1, 5, 10, 2 };Â Â Â Â int N = A.length;Â Â Â Â Â Â Â Â Â System.out.print("(" + findLeastDist(A, N) + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ", " + 0 + ")");}}Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python3 program to implement# the above approachÂ
# Function to find median of the arraydef findLeastDist(A, N):         # Sort the given array    A.sort();Â
    # 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 CodeA = [4, 1, 5, 10, 2];N = len(A);Â
print("(" , findLeastDist(A, N), Â Â Â Â Â Â ", " , 0 , ")");Â
# This code is contributed by PrinciRaj1992 |
C#
// C# program to implement// the above approachusing System;Â
class GFG{Â
// Function to find median of the arraystatic int findLeastDist(int []A, int N){         // Sort the given array    Array.Sort(A);Â
    // 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 Codepublic static void Main(string[] args){Â Â Â Â int []A = { 4, 1, 5, 10, 2 };Â Â Â Â int N = A.Length;Â Â Â Â Â Â Â Â Â Console.Write("(" + findLeastDist(A, N) + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ", " + 0 + ")");}}Â
// This code is contributed by rutvik_56 |
Javascript
<script>Â
// Javascript Program to implement// the above approachÂ
// Function to find median of the arrayfunction findLeastDist(A, N){    // Sort the given array    A.sort((a,b) => a-b);Â
    console.log(A);         // If number of elements are even    if ((N % 2) == 0) {Â
        // Return the first median        return A[parseInt((N - 1) / 2)];    }Â
    // Otherwise    else {        return A[parseInt(N / 2)];    }}Â
// Driver Codevar A = [ 4, 1, 5, 10, 2 ];var N = A.length;document.write( "(" + findLeastDist(A, N)Â Â Â Â Â + ", " + 0 + ")");Â
</script> |
(4, 0)
Time Complexity: O(Nlog(N))
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



