Sum of Manhattan distances between repetitions in a String
Last Updated :
19 Nov, 2021
Given a string S of size N consisting of lowercase characters, the task is to find the sum of Manhattan distance between each pair (i, j) such that i?j and S[j] = S[i].
Examples:
Input: S = “ababa”
Output: 10
Explanation: The pairs having same characters are: (1, 3), (1, 5), (2, 4) and (3, 5). Therefore, the sum of Manhattan distance will be |3 – 1| + |5 – 1| + |4 – 2| + |5 – 3| = 10
Input: S = “abc”
Output: 0
Naive Approach: The simplest approach is to generate all pairs (i, j) using two nested loops and check for each pair, whether it satisfies the given condition or not. If found to be true, add their distances to the answer. After checking all the pairs, print the answer.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The approach is similar to finding the Sum of Manhattan distances between all pairs of points. Follow the steps below to solve the problem:
Let the elements of the vector be x1, x2, x3, x4 which represents the indices of the same character.
This character will contribute value = |x2 – x1| + |x3 – x1| + |x4 – x1| + |x3 – x2| + | x4 – x2| + |x4 – x3|
For a sorted array, this can also be written as (x2 + x3 + x4) – 3*x1 + (x3 + x4) – 2*x2 + (x4) – 1*x3.
Now, the sum can also be expressed as ?suffix[i + 1] – (n-i)*xi for i = 1 to n.
where suffix[i+1] is sum of elements from [i+1, n].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void SumofDistances(string s)
{
vector< int > v[26];
for ( int i = 0; i < s.size(); i++) {
v[s[i] - 'a' ].push_back(i);
}
int ans = 0;
for ( int i = 0; i < 26; i++) {
int sum = 0;
for ( int j = 0; j < v[i].size(); j++) {
sum += v[i][j];
}
for ( int j = 0; j < v[i].size(); j++) {
sum -= v[i][j];
ans += (sum
- (v[i].size() - 1 - j) * (v[i][j]));
}
}
cout << ans;
}
int main()
{
string s = "ababa" ;
SumofDistances(s);
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class GFG{
static void SumofDistances(String s)
{
ArrayList<ArrayList<Integer>> v = new ArrayList<>();
for ( int i = 0 ; i < 26 ; i++)
v.add( new ArrayList<>());
for ( int i = 0 ; i < s.length(); i++)
{
v.get(s.charAt(i) - 'a' ).add(i);
}
int ans = 0 ;
for ( int i = 0 ; i < 26 ; i++)
{
int sum = 0 ;
for ( int j = 0 ; j < v.get(i).size(); j++)
{
sum += v.get(i).get(j);
}
for ( int j = 0 ; j < v.get(i).size(); j++)
{
sum -= v.get(i).get(j);
ans += (sum - (v.get(i).size() - 1 - j) *
(v.get(i).get(j)));
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
String s = "ababa" ;
SumofDistances(s);
}
}
|
Python3
def SumofDistances(s):
v = [[] for i in range ( 26 )]
for i in range ( len (s)):
v[ ord (s[i]) - ord ( 'a' )].append(i)
ans = 0
for i in range ( 26 ):
sum = 0
for j in range ( len (v[i])):
sum + = v[i][j]
for j in range ( len (v[i])):
sum - = v[i][j]
ans + = ( sum - ( len (v[i]) - 1 - j) * (v[i][j]))
print (ans)
if __name__ = = '__main__' :
s = "ababa"
SumofDistances(s)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void SumofDistances( string s)
{
List< int >[] v = new List< int >[26];
for ( int i = 0; i < 26; i++)
v[i] = new List< int >();
for ( int i = 0; i < s.Length; i++)
{
v[( int )s[i] - 97].Add(i);
}
int ans = 0;
for ( int i = 0; i < 26; i++)
{
int sum = 0;
for ( int j = 0; j < v[i].Count; j++)
{
sum += v[i][j];
}
for ( int j = 0; j < v[i].Count; j++)
{
sum -= v[i][j];
ans += (sum - (v[i].Count - 1 - j) *
(v[i][j]));
}
}
Console.Write(ans);
}
public static void Main()
{
string s = "ababa" ;
SumofDistances(s);
}
}
|
Javascript
<script>
function SumofDistances(s)
{
let v = [];
for (let i = 0; i < 26; i++)
v.push([]);
for (let i = 0; i < s.length; i++)
{
v[s[i].charCodeAt(0) - 'a' .charCodeAt(0)].push(i);
}
let ans = 0;
for (let i = 0; i < 26; i++)
{
let sum = 0;
for (let j = 0; j < v[i].length; j++)
{
sum += v[i][j];
}
for (let j = 0; j < v[i].length; j++)
{
sum -= v[i][j];
ans += (sum - (v[i].length - 1 - j) *
(v[i][j]));
}
}
document.write(ans);
}
let s = "ababa" ;
SumofDistances(s);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...