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 ; list to hold the result ; length of string ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > shortestToChar ( string s , char c ) { vector < int > list ; vector < int > res ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( s [ i ] == c ) { list . push_back ( i ) ; } } int p1 , p2 , v1 , v2 ; int l = list . size ( ) - 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 . push_back ( v1 - i ) ; } else if ( i <= v2 ) { if ( i - v1 < v2 - i ) { res . push_back ( i - v1 ) ; } else { res . push_back ( v2 - i ) ; p1 = p2 ; p2 = p2 < l ? ( p2 + 1 ) : p2 ; } } else { res . push_back ( i - v2 ) ; } } return res ; } int main ( ) { string s = " geeksforgeeks " ; char c = ' e ' ; vector < int > res = shortestToChar ( s , c ) ; for ( auto i : res ) cout << i << " ▁ " ; return 0 ; }