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:10Explanation:

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(N^{2}) **Auxiliary Space:** O(1)

Below is the implementation of the above approach:

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `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;` `}` |

*chevron_right*

*filter_none*

## Java

`// 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` |

*chevron_right*

*filter_none*

## Python3

`# 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` |

*chevron_right*

*filter_none*

## C#

`// 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` |

*chevron_right*

*filter_none*

**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.

- Add
- Once the above steps are completed, print the sum obtained.

Below is the implementation of the above approach :

## C++

`// C++ program for the above approach` `#include <bits/stdc++.h>` `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;` `}` |

*chevron_right*

*filter_none*

## Java

`// 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` |

*chevron_right*

*filter_none*

## Python3

`# 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` |

*chevron_right*

*filter_none*

## C#

`// 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` |

*chevron_right*

*filter_none*

**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.

## Recommended Posts:

- Smallest character in a string having minimum sum of distances between consecutive repetitions
- Find the point on X-axis from given N points having least Sum of Distances from all other points
- Minimum Sum of Euclidean Distances to all given Points
- Min flips of continuous characters to make all characters same in a string
- Map every character of one string to another such that all occurrences are mapped to the same character
- Swap all occurrences of two characters to get lexicographically smallest string
- Minimum characters to be replaced to make frequency of all characters same
- String with k distinct characters and no same characters adjacent
- Find a point such that sum of the Manhattan distances is minimized
- Maximum distance between two occurrences of same element in array
- Find the original coordinates whose Manhattan distances are given
- C/C++ program to add N distances given in inch-feet system using Structures
- Group all occurrences of characters according to first appearance
- Count of substrings of a given Binary string with all characters same
- Longest substring between any pair of occurrences ōf similar characters
- Smallest string obtained by removing all occurrences of 01 and 11 from Binary String
- Check whether two strings contain same characters in same order
- Number of permutations of a string in which all the occurrences of a given character occurs together
- Replace all occurrences of pi with 3.14 in a given string
- Replace all occurrences of character X with character Y in given string

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.