Sum of Manhattan distances between repetitions in a String
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].
Input: S = “ababa”
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”
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:
- Initialize a variable ans as 0 to store the required result.
- Create a vector, V for each character to store the positions of each character separately.
- Traverse the string, S, and append the position of each character in their respective vector, V.
- Now, the problem is reduced to finding the sum of the Manhattan distance between each pair of points for each vector array.
- Iterate in the range [0, 25] using the variable i
- Store the sum of all the elements present in the vector, V[i] in a variable sum.
- Traverse the vector, V[i] using the variable j
- Subtract the value of V[i][j] from sum.
- Add the value sum – V[i][j] * (V[i].size() – 1 – j) to ans.
- Print the value of ans as the result.
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:
Time Complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...