Given a string **S** of size **N** consisting of lowercase alphabets only, the task is to find the smallest character having a minimum sum of distances between its consecutive repetition. If string **S** consists of distinct characters only, then print **“-1”**.

**Examples:**

Input:str = “aabbaadc”Output:b;Explanation:

For all the characters in the given string, the sum of the required distances are as follows:

Indices of ‘a’ = {0, 1, 4, 5}

=> Sum of the distances of its next repetition = abs(0 – 1) + abs(4 – 1) + abs(5 – 4) = 5

Indices of ‘b’ = {2, 3}

=> Sum of the distances of its next repetition = abs(2 – 3) = 1

‘c’, ‘d’ has no repetition

From the above distances the minimum sum of distance obtained is 1, for the character ‘b’.

Therefore, the required answer is ‘b’.

Input:str = “abcdef”Output:-1Explanation:

All the characters in the given string are distinct.

**Naive approach:** The simplest approach is to traverse the given string and for each character, find the sum of the shortest distances individually. Print the smallest character with the minimum shortest distance.

**Time Complexity:** O(N*26), where N is the length of the given string.**Auxiliary Space: **O(N)

**Efficient Approach:** The idea is to traverse the string once and find the first and last indices for every character as the sum of the difference between the index between the same characters is the difference between the first and the last character. Follow the below steps to solve the problem:

- Create the arrays
**last[]**and**first[]**having the length equals**26**initialize both the arrays as**-1**. - Initialize
**min**with some large number. - Traverse the string
**S**and update the first occurrence of the current characters to the current index if it equals to**-1**. - Find the last occurrence of each character and store it in the array
**last[]**. - Traverse the array and update the index having a minimum difference at each corresponding if both the index has non-negative value.
- If the minimum index is found at index
**x**, and print the character**(x + ‘a’)**. - Otherwise, print
**“-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 find the character` `// repeats with minimum distance` `char` `minDistChar(string s)` `{` ` ` `int` `n = s.length();` ` ` `// Stores the first and last index` ` ` `int` `* first = ` `new` `int` `[26];` ` ` `int` `* last = ` `new` `int` `[26];` ` ` `// Initialize with -1` ` ` `for` `(` `int` `i = 0; i < 26; i++) {` ` ` `first[i] = -1;` ` ` `last[i] = -1;` ` ` `}` ` ` `// Get the values of last and` ` ` `// first occurence` ` ` `for` `(` `int` `i = 0; i < n; i++) {` ` ` `// Update the first index` ` ` `if` `(first[s[i] - ` `'a'` `] == -1) {` ` ` `first[s[i] - ` `'a'` `] = i;` ` ` `}` ` ` `// Update the last index` ` ` `last[s[i] - ` `'a'` `] = i;` ` ` `}` ` ` `// Initialize min` ` ` `int` `min = INT_MAX;` ` ` `char` `ans = ` `'1'` `;` ` ` `// Get the minimum` ` ` `for` `(` `int` `i = 0; i < 26; i++) {` ` ` `// Values must not be same` ` ` `if` `(last[i] == first[i])` ` ` `continue` `;` ` ` `// Update the minimum distance` ` ` `if` `(min > last[i] - first[i]) {` ` ` `min = last[i] - first[i];` ` ` `ans = i + ` `'a'` `;` ` ` `}` ` ` `}` ` ` `// return ans` ` ` `return` `ans;` `}` `// Driver Code` `int` `main()` `{` ` ` `string str = ` `"geeksforgeeks"` `;` ` ` `// Function Call` ` ` `cout << minDistChar(str);` ` ` `return` `0;` `}` |

*chevron_right*

*filter_none*

## Java

`// Java program for ` `// the above approach` `import` `java.util.*;` `class` `GFG{` `// Function to find the character` `// repeats with minimum distance` `static` `char` `minDistChar(` `char` `[]s)` `{` `int` `n = s.length;` `// Stores the first and last index` `int` `[]first = ` `new` `int` `[` `26` `];` `int` `[]last = ` `new` `int` `[` `26` `];` `// Initialize with -1` `for` `(` `int` `i = ` `0` `; i < ` `26` `; i++) ` `{` ` ` `first[i] = -` `1` `;` ` ` `last[i] = -` `1` `;` `}` `// Get the values of last and` `// first occurence` `for` `(` `int` `i = ` `0` `; i < n; i++) ` `{` ` ` `// Update the first index` ` ` `if` `(first[s[i] - ` `'a'` `] == -` `1` `) ` ` ` `{` ` ` `first[s[i] - ` `'a'` `] = i;` ` ` `}` ` ` `// Update the last index` ` ` `last[s[i] - ` `'a'` `] = i;` `}` `// Initialize min` `int` `min = Integer.MAX_VALUE;` `char` `ans = ` `'1'` `;` `// Get the minimum` `for` `(` `int` `i = ` `0` `; i < ` `26` `; i++) ` `{` ` ` `// Values must not be same` ` ` `if` `(last[i] == first[i])` ` ` `continue` `;` ` ` `// Update the minimum distance` ` ` `if` `(min > last[i] - first[i]) ` ` ` `{` ` ` `min = last[i] - first[i];` ` ` `ans = (` `char` `) (i + ` `'a'` `);` ` ` `}` `}` `// return ans` `return` `ans;` `}` `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `String str = ` `"geeksforgeeks"` `;` `// Function Call` `System.out.print(minDistChar(str.toCharArray()));` `}` `}` `// This code is contributed by shikhasingrajput` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program for the above approach` `import` `sys` `# Function to find the character` `# repeats with minimum distance` `def` `minDistChar(s):` ` ` ` ` `n ` `=` `len` `(s)` ` ` ` ` `# Stores the first and last index` ` ` `first ` `=` `[]` ` ` `last ` `=` `[]` ` ` ` ` `# Intialize with -1` ` ` `for` `i ` `in` `range` `(` `26` `):` ` ` `first.append(` `-` `1` `)` ` ` `last.append(` `-` `1` `)` ` ` ` ` `# Get the values of last and` ` ` `# first occurence` ` ` `for` `i ` `in` `range` `(n):` ` ` ` ` `# Update the first index` ` ` `if` `(first[` `ord` `(s[i]) ` `-` `ord` `(` `'a'` `)] ` `=` `=` `-` `1` `):` ` ` `first[` `ord` `(s[i]) ` `-` `ord` `(` `'a'` `)] ` `=` `i` ` ` ` ` `# Update the last index` ` ` `last[` `ord` `(s[i]) ` `-` `ord` `(` `'a'` `)] ` `=` `i` ` ` ` ` `# Intialize the min` ` ` `min` `=` `sys.maxsize` ` ` `ans ` `=` `'1'` ` ` ` ` `# Get the minimum` ` ` `for` `i ` `in` `range` `(` `26` `):` ` ` ` ` `# Values must not be same` ` ` `if` `(last[i] ` `=` `=` `first[i]):` ` ` `continue` ` ` ` ` `# Update the minimum distance` ` ` `if` `(` `min` `> last[i] ` `-` `first[i]):` ` ` `min` `=` `last[i] ` `-` `first[i]` ` ` `ans ` `=` `i ` `+` `ord` `(` `'a'` `)` ` ` ` ` `return` `chr` `(ans)` ` ` `# Driver Code` `if` `__name__ ` `=` `=` `"__main__"` `:` ` ` ` ` `str` `=` `"geeksforgeeks"` ` ` `# Function call` ` ` `print` `(minDistChar(` `str` `))` `# This code is contributed by dadi madhav` |

*chevron_right*

*filter_none*

## C#

`// C# program for the above approach ` `using` `System; ` `using` `System.Collections.Generic; ` `class` `GFG{ ` ` ` `// Function to find the character` `// repeats with minimum distance` `static` `char` `minDistChar(` `char` `[]s)` `{` ` ` `int` `n = s.Length;` ` ` `// Stores the first and last index` ` ` `int` `[]first = ` `new` `int` `[26];` ` ` `int` `[]last = ` `new` `int` `[26];` ` ` `// Initialize with -1` ` ` `for` `(` `int` `i = 0; i < 26; i++) ` ` ` `{` ` ` `first[i] = -1;` ` ` `last[i] = -1;` ` ` `}` ` ` `// Get the values of last and` ` ` `// first occurence` ` ` `for` `(` `int` `i = 0; i < n; i++) ` ` ` `{` ` ` `// Update the first index` ` ` `if` `(first[s[i] - ` `'a'` `] == -1) ` ` ` `{` ` ` `first[s[i] - ` `'a'` `] = i;` ` ` `}` ` ` `// Update the last index` ` ` `last[s[i] - ` `'a'` `] = i;` ` ` `}` ` ` `// Initialize min` ` ` `int` `min = ` `int` `.MaxValue;` ` ` `char` `ans = ` `'1'` `;` ` ` `// Get the minimum` ` ` `for` `(` `int` `i = 0; i < 26; i++) ` ` ` `{` ` ` `// Values must not be same` ` ` `if` `(last[i] == first[i])` ` ` `continue` `;` ` ` `// Update the minimum distance` ` ` `if` `(min > last[i] - first[i]) ` ` ` `{` ` ` `min = last[i] - first[i];` ` ` `ans = (` `char` `)(i + ` `'a'` `);` ` ` `}` ` ` `}` ` ` ` ` `// return ans` ` ` `return` `ans;` `}` ` ` `// Driver Code ` `public` `static` `void` `Main(` `string` `[] args) ` `{ ` ` ` `String str = ` `"geeksforgeeks"` `;` ` ` ` ` `// Function call` ` ` `Console.Write(minDistChar(str.ToCharArray()));` `} ` `} ` `// This code is contributed by rutvik_56` |

*chevron_right*

*filter_none*

**Output:**

g

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

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:

- Maximize minimum distance between repetitions from any permutation of the given Array
- Find the point on X-axis from given N points having least Sum of Distances from all other points
- Sum of all distances between occurrences of same characters in a given string
- Represent N as sum of K even or K odd numbers with repetitions allowed
- Minimum Sum of Euclidean Distances to all given Points
- Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
- Split array into two equal length subsets such that all repetitions of a number lies in a single subset
- Count of substrings having the most frequent character in the string as first character
- Sum of the distances from every node to all other nodes is maximum
- Count of strings possible by replacing two consecutive same character with new character
- Convert given string to another by minimum replacements of subsequences by its smallest character
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- String generated by typing given string in a keyboard having the button of given character faulty
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Generate a Binary String without any consecutive 0's and at most K consecutive 1's
- Maximum consecutive repeating character in string
- Find a string such that every character is lexicographically greater than its immediate next character
- Replace every character of string by character whose ASCII value is K times more than it

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.