Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 points
int 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 code
int 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 points
def 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 code
arr = [4, 1, 5, 10, 2]
n = len(arr)
 
# Function call to find the point with the least sum of
# distances from all other points
idx = leastSumOfDistances(arr, n)
 
# Printing the result
print("({}, {})".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)");
    }
}


Javascript




// Function to find the point with the least sum of distances from all other points
function leastSumOfDistances(arr) {
    // Initialize the minimum sum of distances with infinity
    let minSum = Infinity;
 
    // Initialize the index of the element with minimum sum of distances as -1
    let idx = -1;
 
    // Iterate over each point
    for (let i = 0; i < arr.length; i++) {
        // Initialize the sum of distances for the current point to zero
        let sum = 0;
 
        // Calculate the sum of distances of the current point from all other points
        for (let j = 0; j < arr.length; 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 the minimum sum of distances
    return idx;
}
 
// Driver code
const arr = [4, 1, 5, 10, 2];
 
// Function call to find the point with the least sum of distances from all other points
const idx = leastSumOfDistances(arr);
 
// Printing the result
console.log(`(${arr[idx]}, 0)`);


Output

(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 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;
}


Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to find median of the array
static 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 Code
public 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 array
def 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 Code
A = [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 approach
using System;
 
class GFG{
 
// Function to find median of the array
static 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 Code
public 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 array
function 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 Code
var A = [ 4, 1, 5, 10, 2 ];
var N = A.length;
document.write( "(" + findLeastDist(A, N)
     + ", " + 0 + ")");
 
</script>


Output

(4, 0)




Time Complexity: O(Nlog(N))
Auxiliary Space: O(1)



Last Updated : 09 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads