text: Shortest distance to every other character from given character | C implementation of above approach ; Function to return required vector of distances ; list to hold position of c in s ; length of string ; To hold size of list ; Iterate over string to create list ; max value of p2 ; Initialize the pointers ; Create result array ; Values at current pointers ; Current Index is before than p1 ; Current Index is between p1 and p2 ; Current Index is nearer to p1 ; Current Index is nearer to p2 ; Move pointer 1 step ahead ; Current index is after p2 ; Driver code
code: #include <stdio.h> NEW_LINE #define MAX_SIZE  100 NEW_LINE void shortestToChar ( char s [ ] , char c , int * res ) { int list [ MAX_SIZE ] ; int len = 0 ; int l = 0 ; while ( s [ len ] != ' \0' ) { if ( s [ len ] == c ) { list [ l ] = len ; l ++ ; } len ++ ; } int p1 , p2 , v1 , v2 ; l = l - 1 ; p1 = 0 ; p2 = l > 0 ? 1 : 0 ; for ( int i = 0 ; i < len ; i ++ ) { v1 = list [ p1 ] ; v2 = list [ p2 ] ; if ( i <= v1 ) { res [ i ] = ( v1 - i ) ; } else if ( i <= v2 ) { if ( i - v1 < v2 - i ) { res [ i ] = ( i - v1 ) ; } else { res [ i ] = ( v2 - i ) ; p1 = p2 ; p2 = p2 < l ? ( p2 + 1 ) : p2 ; } } else { res [ i ] = ( i - v2 ) ; } } } int main ( ) { char s [ ] = " geeksforgeeks " ; char c = ' e ' ; int res [ MAX_SIZE ] ; shortestToChar ( s , c , res ) ; int i = 0 ; while ( s [ i ] != ' \0' ) printf ( " % d ▁ " , res [ i ++ ] ) ; return 0 ; }