text: Smallest character in a string having minimum sum of distances between consecutive repetitions | C ++ program for the above approach ; Function to find the character repeats with minimum distance ; Stores the first and last index ; Initialize with - 1 ; Get the values of last and first occurence ; Update the first index ; Update the last index ; Initialize min ; Get the minimum ; Values must not be same ; Update the minimum distance ; return ans ; Driver Code ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; char minDistChar ( string s ) { int n = s . length ( ) ; int * first = new int [ 26 ] ; int * last = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { first [ i ] = -1 ; last [ i ] = -1 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( first [ s [ i ] - ' a ' ] == -1 ) { first [ s [ i ] - ' a ' ] = i ; } last [ s [ i ] - ' a ' ] = i ; } int min = INT_MAX ; char ans = '1' ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( last [ i ] == first [ i ] ) continue ; if ( min > last [ i ] - first [ i ] ) { min = last [ i ] - first [ i ] ; ans = i + ' a ' ; } } return ans ; } int main ( ) { string str = " geeksforgeeks " ; cout << minDistChar ( str ) ; return 0 ; }