# Sum of all distances between occurrences of same characters in a given string

Given a string S, the task is to find the sum of distances between all pairs of indices from the given string which contains the same character.

Examples:

Input: S = “ababa”
Output: 10
Explanation:
The pair of indices having same character are: (0, 2) (0, 4) (1, 3) (2, 4)
Sum of absolute differences between these pair of indices = |2 – 0| + |4 – 0| + |1 – 3| + |2 – 4| = 10.
Therefore, the required answer is 10.

Input: S = “ttt”
Output: 4

Naive Approach: The simplest approach to solve the problem is to traverse the string and for each character encountered, traverse the remaining string on its right to find occurrences of that character. For every repetition of characters found, keep adding the absolute difference between the concerned indices to the answer. Finally, print the sum obtained.

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

Below is the implementation of the above approach:

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a string` `int` `findSum(string s)` `{` `    ``int` `sum = 0;` `    ``for` `(``int` `i = 0; i < s.size(); i++) {` `        ``for` `(``int` `j = i + 1; j < s.size(); j++) {`   `            ``// If similar characters are found` `            ``if` `(s[i] == s[j]) {`   `                ``// Add the difference` `                ``// of their positions` `                ``sum += (j - i);` `            ``}` `        ``}` `    ``}`   `    ``// Return the answer` `    ``return` `sum;` `}`   `// Driver Code` `int` `main()` `{` `    ``string s = ``"ttt"``;` `    ``cout << findSum(s) << endl;` `}`

 `// Java program for the above approach` `import` `java.util.*;` `class` `GFG{`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a String` `static` `int` `findSum(String s)` `{` `    ``int` `sum = ``0``;` `    ``for` `(``int` `i = ``0``; i < s.length(); i++) ` `    ``{` `        ``for` `(``int` `j = i + ``1``; j < s.length(); j++) ` `        ``{` `            ``// If similar characters are found` `            ``if` `(s.charAt(i) == s.charAt(j)) ` `            ``{` `                ``// Add the difference` `                ``// of their positions` `                ``sum += (j - i);` `            ``}` `        ``}` `    ``}`   `    ``// Return the answer` `    ``return` `sum;` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    ``String s = ``"ttt"``;` `    ``System.out.print(findSum(s) + ``"\n"``);` `}` `}` `// This code is contributed by shikhasingrajput`

 `# Python3 program for the above approach ` ` `  `# Function to calculate the sum` `# of distances between occurrences` `# of same characters in a string` `def` `findSum(s):` `    `  `    ``sum` `=` `0` `    ``for` `i ``in` `range``(``len``(s)):` `        ``for` `j ``in` `range``(i ``+` `1``, ``len``(s)):` ` `  `            ``# If similar characters are found` `            ``if` `(s[i] ``=``=` `s[j]):` ` `  `                ``# Add the difference` `                ``# of their positions` `                ``sum` `+``=` `(j ``-` `i)` ` `  `    ``# Return the answer` `    ``return` `sum`   `# Driver Code` `s ``=` `"ttt"`   `print``(findSum(s))`   `# This code is contributed by code_hunt`

 `// C# program for ` `// the above approach` `using` `System;` `class` `GFG{`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a String` `static` `int` `findSum(String s)` `{` `  ``int` `sum = 0;` `  ``for` `(``int` `i = 0; i < s.Length; i++) ` `  ``{` `    ``for` `(``int` `j = i + 1; j < s.Length; j++) ` `    ``{` `      ``// If similar characters ` `      ``// are found` `      ``if` `(s[i] == s[j]) ` `      ``{` `        ``// Add the difference` `        ``// of their positions` `        ``sum += (j - i);` `      ``}` `    ``}` `  ``}`   `  ``// Return the answer` `  ``return` `sum;` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `  ``String s = ``"ttt"``;` `  ``Console.Write(findSum(s) + ``"\n"``);` `}` `}` ` `  `// This code is contributed by shikhasingrajput`

Output:
```4

```

Efficient Approach: The above approach can be optimized based on the following observations:

• Initially for every character, assume that all its similar characters are at index 0.
• With the above assumption, the required sum becomes equal to:

Number of previously visited similar characters * Index of the character – sum of distances of those similar characters from index 0

Therefore, follow the steps below to solve the problem:

• Initialize two arrays visited[] and distance[] to store the frequency of each character present in the string and the distance between the previous occurrences of each character respectively.
• Traverse the string and for every character encountered, i.e. S[i], update the following:
• Add visited[S[i] * i – distance[S[i]] to the required sum.
• Increment visited[S[i]] to increase frequency of characters.
• Increase distance[S[i]] by i, to increase the distance from the previous occurrence of S[i], considered to be 0.
• Once the above steps are completed, print the sum obtained.

Below is the implementation of the above approach :

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a string` `int` `findSum(string s)` `{` `    ``int` `visited[256];` `    ``int` `distance[256];`   `    ``// Initially make all the distances` `    ``// and number of characters visited as 0` `    ``for` `(``int` `i = 0; i < 256; i++) {` `        ``visited[i] = 0;` `        ``distance[i] = 0;` `    ``}`   `    ``int` `sum = 0;`   `    ``for` `(``int` `i = 0; i < s.size(); i++) {`   `        ``// Assuming that all the similar` `        ``// characters are located at index 0`   `        ``// Add visited[s[i]]*i to sum` `        ``// and subtract the distances of` `        ``// characters from index 0` `        ``sum += visited[s[i]] * i` `               ``- distance[s[i]];`   `        ``// Increment the number of` `        ``// visited characters` `        ``visited[s[i]]++;`   `        ``// Add the distance of the` `        ``// character from position 0` `        ``// i.e., (i - 0) = i` `        ``distance[s[i]] += i;` `    ``}`   `    ``// Return the answer` `    ``return` `sum;` `}`   `// Driver code` `int` `main()` `{` `    ``string s = ``"ttt"``;`   `    ``// Function call` `    ``cout << findSum(s) << endl;` `}`

 `// Java program for the above approach` `import` `java.io.*;`   `class` `GFG{`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a string` `static` `int` `findSum(String s)` `{` `    ``int``[] visited = ``new` `int``[``256``];` `    ``int``[] distance = ``new` `int``[``256``];`   `    ``// Initially make all the distances` `    ``// and number of characters visited as 0` `    ``for``(``int` `i = ``0``; i < ``256``; i++)` `    ``{` `        ``visited[i] = ``0``;` `        ``distance[i] = ``0``;` `    ``}`   `    ``int` `sum = ``0``;`   `    ``for``(``int` `i = ``0``; i < s.length(); i++)` `    ``{` `        `  `        ``// Assuming that all the similar` `        ``// characters are located at index 0`   `        ``// Add visited[s[i]]*i to sum` `        ``// and subtract the distances of` `        ``// characters from index 0` `        ``sum += visited[s.charAt(i)] * i - ` `              ``distance[s.charAt(i)];`   `        ``// Increment the number of` `        ``// visited characters` `        ``visited[s.charAt(i)]++;`   `        ``// Add the distance of the` `        ``// character from position 0` `        ``// i.e., (i - 0) = i` `        ``distance[s.charAt(i)] += i;` `    ``}`   `    ``// Return the answer` `    ``return` `sum;` `} `   `// Driver code` `public` `static` `void` `main (String[] args)` `{` `    ``String s = ``"ttt"``;` `    `  `    ``// Function call` `    ``System.out.println(findSum(s));` `}` `}`   `// This code is contributed by offbeat`

 `# Python3 program for the above approach`   `# Function to calculate the sum` `# of distances between occurrences` `# of same characters in a string` `def` `findSum(s):` `    ``visited ``=` `[``0` `for` `i ``in` `range``(``256``)];` `    ``distance ``=` `[``0` `for` `i ``in` `range``(``256``)];`   `    ``# Initially make all ` `    ``# the distances and number ` `    ``# of characters visited as 0` `    ``for` `i ``in` `range``(``256``):` `        ``visited[i] ``=` `0``;` `        ``distance[i] ``=` `0``;    `   `    ``sum` `=` `0``;`   `    ``for` `i ``in` `range``(``len``(s)):`   `        ``# Assuming that all the similar` `        ``# characters are located at index 0`   `        ``# Add visited[s[i]]*i to sum` `        ``# and subtract the distances of` `        ``# characters from index 0` `        ``sum` `+``=` `visited[``ord``(s[i])] ``*` `i ``-` `distance[``ord``(s[i])];`   `        ``# Increment the number of` `        ``# visited characters` `        ``visited[``ord``(s[i])] ``+``=` `1``;`   `        ``# Add the distance of the` `        ``# character from position 0` `        ``# i.e., (i - 0) = i` `        ``distance[``ord``(s[i])] ``+``=` `i;    `   `    ``# Return the answer` `    ``return` `sum``;`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `  `  `    ``s ``=` `"ttt"``;`   `    ``# Function call` `    ``print``(findSum(s));`   `# This code is contributed by Rajput-Ji`

 `// C# program for the above approach` `using` `System;`   `class` `GFG{`   `// Function to calculate the sum` `// of distances between occurrences` `// of same characters in a string` `static` `int` `findSum(String s)` `{` `    ``int``[] visited = ``new` `int``[256];` `    ``int``[] distance = ``new` `int``[256];`   `    ``// Initially make all the distances` `    ``// and number of characters visited as 0` `    ``for``(``int` `i = 0; i < 256; i++)` `    ``{` `        ``visited[i] = 0;` `        ``distance[i] = 0;` `    ``}` `    `  `    ``int` `sum = 0;` `    `  `    ``for``(``int` `i = 0; i < s.Length; i++)` `    ``{` `        `  `        ``// Assuming that all the similar` `        ``// characters are located at index 0`   `        ``// Add visited[s[i]]*i to sum` `        ``// and subtract the distances of` `        ``// characters from index 0` `        ``sum += visited[s[i]] * i - ` `              ``distance[s[i]];`   `        ``// Increment the number of` `        ``// visited characters` `        ``visited[s[i]]++;`   `        ``// Add the distance of the` `        ``// character from position 0` `        ``// i.e., (i - 0) = i` `        ``distance[s[i]] += i;` `    ``}`   `    ``// Return the answer` `    ``return` `sum;` `} `   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `    ``String s = ``"ttt"``;` `    `  `    ``// Function call` `    ``Console.WriteLine(findSum(s));` `}` `}`   `// This code is contributed by Amit Katiyar`

Output:
```4

```

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :