Open In App

Sum of Manhattan distances between all pairs of points

Improve
Improve
Like Article
Like
Save
Share
Report

Given n integer coordinates. The task is to find sum of manhattan distance between all pairs of coordinates. 
Manhattan Distance between two points (x1, y1) and (x2, y2) is: 
|x1 – x2| + |y1 – y2|
Examples : 

Input : n = 4
        point1 = { -1, 5 }
        point2 = { 1, 6 }
        point3 = { 3, 5 }
        point4 = { 2, 3 }
Output : 22
Distance of { 1, 6 }, { 3, 5 }, { 2, 3 } from 
{ -1, 5 } are 3, 4, 5 respectively.
Therefore, sum = 3 + 4 + 5 = 12

Distance of { 3, 5 }, { 2, 3 } from { 1, 6 } 
are 3, 4 respectively.
Therefore, sum = 12 + 3 + 4 = 19

Distance of { 2, 3 } from { 3, 5 } is 3.
Therefore, sum = 19 + 3 = 22.

Method 1: (Brute Force) 

Time Complexity: O(n2)
The idea is to run two nested loop i.e for each point, find manhattan distance for all other points.  

for (i = 1; i < n; i++)

  for (j = i + 1; j < n; j++)

    sum += ((xi - xj) + (yi - yj))

Below is the implementation of this approach:  

C++





C




// C Program to find sum of Manhattan distance
// between all the pairs of given points
#include <stdio.h>
#include <stdlib.h>
 
// Return the sum of distance between all
// the pair of points.
int distancesum(int x[], int y[], int n)
{
    int sum = 0;
 
    // for each point, finding distance to
    // rest of the point
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            sum += (abs(x[i] - x[j]) + abs(y[i] - y[j]));
    return sum;
}
 
// Driven Program
int main()
{
    int x[] = { -1, 1, 3, 2 };
    int y[] = { 5, 6, 5, 3 };
    int n = sizeof(x) / sizeof(x[0]);
    printf("%d\n", distancesum(x, y, n));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java Program to find sum of Manhattan distance
// between all the pairs of given points
 
import java.io.*;
 
class GFG {
 
    // Return the sum of distance between all
    // the pair of points.
    static int distancesum(int x[], int y[], int n)
    {
        int sum = 0;
 
        // for each point, finding distance to
        // rest of the point
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                sum += (Math.abs(x[i] - x[j])
                        + Math.abs(y[i] - y[j]));
        return sum;
    }
 
    // Driven Program
    public static void main(String[] args)
    {
        int x[] = { -1, 1, 3, 2 };
        int y[] = { 5, 6, 5, 3 };
        int n = x.length;
 
        System.out.println(distancesum(x, y, n));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 code to find sum of
# Manhattan distance between all
# the pairs of given points
 
# Return the sum of distance
# between all the pair of points.
def distancesum (x, y, n):
    sum = 0
     
    # for each point, finding distance
    # to rest of the point
    for i in range(n):
        for j in range(i+1,n):
            sum += (abs(x[i] - x[j]) +
                        abs(y[i] - y[j]))
     
    return sum
 
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(distancesum(x, y, n) )
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# Program to find sum of Manhattan distance
// between all the pairs of given points
using System;
 
class GFG {
     
    // Return the sum of distance between all
    // the pair of points.
    static int distancesum(int []x, int []y, int n)
    {
        int sum = 0;
 
        // for each point, finding distance to
        // rest of the point
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                sum += (Math.Abs(x[i] - x[j]) +
                            Math.Abs(y[i] - y[j]));
        return sum;
    }
 
    // Driven Program
    public static void Main()
    {
        int []x = { -1, 1, 3, 2 };
        int []y = { 5, 6, 5, 3 };
        int n = x.Length;
         
        Console.WriteLine(distancesum(x, y, n));
    }
}
 
// This code is contributed by vt_m.


PHP





Javascript




<script>
 
// JavaScript Program to find sum of Manhattan distance
// between all the pairs of given points
 
    // Return the sum of distance between all
    // the pair of points.
    function distancesum(x, y, n)
    {
        let sum = 0;
  
        // for each point, finding distance to
        // rest of the point
        for (let i = 0; i < n; i++)
            for (let j = i + 1; j < n; j++)
                sum += (Math.abs(x[i] - x[j]) +
                            Math.abs(y[i] - y[j]));
        return sum;
    }
 
// Driver code
        let x = [ -1, 1, 3, 2 ];
        let y = [ 5, 6, 5, 3 ];
        let n = x.length;
          
        document.write(distancesum(x, y, n));
          
         // This code is contributed by sanjoy_62.
</script>


Output:  

22

Time Complexity: O(n2
Auxiliary Space: O(1)

Method 2: (Efficient Approach) 

  1. The idea is to use Greedy Approach. First observe, the manhattan formula can be decomposed into two independent sums, one for the difference between x coordinates and the second between y coordinates. If we know how to compute one of them we can use the same method to compute the other. So now we will stick to compute the sum of x coordinates distance.
  2. Let’s assume that we have calculated the sum of distances between any two points till a point xi-1 for all values of x‘s smaller than xi-1 , let this sum be res and now we have to calculate the distance between any two points with xi included, where xi is the next greater point, To calculate the distance of each point from the next greater point xi ,  we can add the existing sum of differences res with the distance of xi from all the points xk which are less than xi. Hence the sum between any two points will now be equal to res + ?(xi xk) , where xi is the current point from which differences are being measured, and xk are all the points less than xi.
  3. Because for every calculation xi remains same, we can simplify the summation as :

res = res + (xi – x0) + (xi – x1) + (xi – x2) + (xi – x3)………(xi – xi-1)

res = res + (xi)*i – (x0 +x1 + x2 + …… xi-1) , because in a sorted array, there are i elements smaller than the current index i .

res = res + (xi)*i – Si-1  , where Si-1 is the sum of all the previous points till index i – 1

        4. For the new index i , we need to add the difference of the current index xi from all the previous indices x < xi

        5. If we sort all points in non-decreasing order, we can easily compute the desired sum of distances along one axis between each pair of coordinates in O(N) time, processing points from left to right and using the above method. 
Also, we don’t have to concern if two points are equal coordinates, after sorting points in non-decreasing order, we say that a point xi-1 is smaller xi if and only if it appears earlier in the sorted array.
Below is the implementation of this approach: 

C++




// CPP Program to find sum of Manhattan
// distances between all the pairs of
// given points
#include <bits/stdc++.h>
using namespace std;
 
// Return the sum of distance of one axis.
int distancesum(int arr[], int n)
{
    // sorting the array.
    sort(arr, arr + n);
 
    // for each point, finding the distance.
    int res = 0, sum = 0;
    for (int i = 0; i < n; i++) {
        res += (arr[i] * i - sum);
        sum += arr[i];
    }
 
    return res;
}
 
int totaldistancesum(int x[], int y[], int n)
{
    return distancesum(x, n) + distancesum(y, n);
}
 
// Driven Program
int main()
{
    int x[] = { -1, 1, 3, 2 };
    int y[] = { 5, 6, 5, 3 };
    int n = sizeof(x) / sizeof(x[0]);
    cout << totaldistancesum(x, y, n) << endl;
    return 0;
}


Java




// Java Program to find sum of Manhattan
// distances between all the pairs of
// given points
 
import java.io.*;
import java.util.*;
 
class GFG {
     
    // Return the sum of distance of one axis.
    static int distancesum(int arr[], int n)
    {
         
        // sorting the array.
        Arrays.sort(arr);
 
        // for each point, finding the distance.
        int res = 0, sum = 0;
        for (int i = 0; i < n; i++) {
            res += (arr[i] * i - sum);
            sum += arr[i];
        }
 
        return res;
    }
 
    static int totaldistancesum(int x[],
                            int y[], int n)
    {
        return distancesum(x, n) +
                        distancesum(y, n);
    }
 
    // Driven Program
    public static void main(String[] args)
    {
 
        int x[] = { -1, 1, 3, 2 };
        int y[] = { 5, 6, 5, 3 };
        int n = x.length;
        System.out.println(totaldistancesum(x,
                                        y, n));
    }
}
 
// This code is contributed by vt_m.


Python3




# Python3 code to find sum of Manhattan
# distances between all the pairs of
# given points
 
# Return the sum of distance of one axis.
def distancesum (arr, n):
     
    # sorting the array.
    arr.sort()
     
    # for each point, finding
    # the distance.
    res = 0
    sum = 0
    for i in range(n):
        res += (arr[i] * i - sum)
        sum += arr[i]
     
    return res
     
def totaldistancesum( x , y , n ):
    return distancesum(x, n) + distancesum(y, n)
     
# Driven Code
x = [ -1, 1, 3, 2 ]
y = [ 5, 6, 5, 3 ]
n = len(x)
print(totaldistancesum(x, y, n) )
 
# This code is contributed by "Sharad_Bhardwaj".


C#




// C# Program to find sum of Manhattan
// distances between all the pairs of
// given points
 
using System;
 
class GFG {
     
    // Return the sum of distance of one axis.
    static int distancesum(int []arr, int n)
    {
         
        // sorting the array.
        Array.Sort(arr);
 
        // for each point, finding the distance.
        int res = 0, sum = 0;
        for (int i = 0; i < n; i++) {
            res += (arr[i] * i - sum);
            sum += arr[i];
        }
 
        return res;
    }
 
    static int totaldistancesum(int []x,
                            int []y, int n)
    {
        return distancesum(x, n) +
                        distancesum(y, n);
    }
 
    // Driven Program
    public static void Main()
    {
 
        int []x = { -1, 1, 3, 2 };
        int []y = { 5, 6, 5, 3 };
        int n = x.Length;
        Console.WriteLine(totaldistancesum(x,
                                        y, n));
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP Program to find sum of
// Manhattan distances between
// all the pairs of given points
 
// Return the sum of
// distance of one axis.
function distancesum($arr, $n)
{
    // sorting the array.
    sort($arr);
 
    // for each point,
    // finding the distance.
    $res = 0; $sum = 0;
    for ($i = 0; $i < $n; $i++)
    {
        $res += ($arr[$i] * $i - $sum);
        $sum += $arr[$i];
    }
 
    return $res;
}
 
function totaldistancesum($x, $y, $n)
{
    return distancesum($x, $n) +
           distancesum($y, $n);
}
 
// Driver Code
$x = array(-1, 1, 3, 2);
$y = array(5, 6, 5, 3);
$n = sizeof($x);
echo totaldistancesum($x, $y, $n), "\n";
 
// This code is contributed by m_kit
?>


Javascript




<script>
 
// JavaScript Program to find sum of Manhattan
// distances between all the pairs of
// given points
 
    // Return the sum of distance of one axis.
    function distancesum(arr, n)
    {
          
        // sorting the array.
        arr.sort();
  
        // for each point, finding the distance.
        let res = 0, sum = 0;
        for (let i = 0; i < n; i++) {
            res += (arr[i] * i - sum);
            sum += arr[i];
        }
  
        return res;
    }
  
    function totaldistancesum(x,
                            y, n)
    {
        return distancesum(x, n) +
                        distancesum(y, n);
    }
      
 
// Driver code
         
        let x = [ -1, 1, 3, 2 ];
        let y = [ 5, 6, 5, 3 ];
        let n = x.length;
        document.write(totaldistancesum(x,
                                        y, n));
                   
</script>


Output : 

22

Time Complexity : O(n log n) 
Auxiliary Space: O(1)



Last Updated : 20 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads