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++
#include <bits/stdc++.h>
using namespace std;
int distancesum( int x[], int y[], int n)
{
int sum = 0;
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;
}
int main()
{
int x[] = { -1, 1, 3, 2 };
int y[] = { 5, 6, 5, 3 };
int n = sizeof (x) / sizeof (x[0]);
cout << distancesum(x, y, n) << endl;
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
int distancesum( int x[], int y[], int n)
{
int sum = 0;
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;
}
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;
}
|
Java
import java.io.*;
class GFG {
static int distancesum( int x[], int y[], int n)
{
int sum = 0 ;
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;
}
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));
}
}
|
Python3
def distancesum (x, y, n):
sum = 0
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
x = [ - 1 , 1 , 3 , 2 ]
y = [ 5 , 6 , 5 , 3 ]
n = len (x)
print (distancesum(x, y, n) )
|
C#
using System;
class GFG {
static int distancesum( int []x, int []y, int n)
{
int sum = 0;
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;
}
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));
}
}
|
PHP
<?php
function distancesum( $x , $y , $n )
{
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
$sum += ( abs ( $x [ $i ] - $x [ $j ]) +
abs ( $y [ $i ] - $y [ $j ]));
return $sum ;
}
$x = array (-1, 1, 3, 2);
$y = array (5, 6, 5, 3);
$n = count ( $x );
echo distancesum( $x , $y , $n );
?>
|
Javascript
<script>
function distancesum(x, y, n)
{
let sum = 0;
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;
}
let x = [ -1, 1, 3, 2 ];
let y = [ 5, 6, 5, 3 ];
let n = x.length;
document.write(distancesum(x, y, n));
</script>
|
Output:
22
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2: (Efficient Approach)
- 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.
- 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.
- 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 xk < 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++
#include <bits/stdc++.h>
using namespace std;
int distancesum( int arr[], int n)
{
sort(arr, arr + n);
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);
}
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
import java.io.*;
import java.util.*;
class GFG {
static int distancesum( int arr[], int n)
{
Arrays.sort(arr);
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);
}
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));
}
}
|
Python3
def distancesum (arr, n):
arr.sort()
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)
x = [ - 1 , 1 , 3 , 2 ]
y = [ 5 , 6 , 5 , 3 ]
n = len (x)
print (totaldistancesum(x, y, n) )
|
C#
using System;
class GFG {
static int distancesum( int []arr, int n)
{
Array.Sort(arr);
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);
}
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));
}
}
|
PHP
<?php
function distancesum( $arr , $n )
{
sort( $arr );
$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 );
}
$x = array (-1, 1, 3, 2);
$y = array (5, 6, 5, 3);
$n = sizeof( $x );
echo totaldistancesum( $x , $y , $n ), "\n" ;
?>
|
Javascript
<script>
function distancesum(arr, n)
{
arr.sort();
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);
}
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)
This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above