text: Smallest character in a string having minimum sum of distances between consecutive repetitions | Function to find the let acter 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: function minDistChar ( s ) { let n = s . length ; let first = new Array ( 26 ) ; let last = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { first [ i ] = - 1 ; last [ i ] = - 1 ; } for ( let i = 0 ; i < n ; i ++ ) { if ( first [ s [ i ] - ' ' ] == - 1 ) { first [ s [ i ] - ' ' ] = i ; } last [ s [ i ] - ' ' ] = i ; } let min = 100000 ; var ans = ' ' ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( last [ i ] == first [ i ] ) continue ; if ( min > last [ i ] - first [ i ] ) { min = last [ i ] - first [ i ] ; ans = String . fromCharCode ( i + 97 ) ; } } return ans ; } str = " " ; document . write ( minDistChar ( str ) ) ;