Now follow the algorithm discussed in below
for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int visited [ 256 ] = { 0 } ; string sub_str = " " ; for ( int j = i ; j < n ; j ++ ) { if ( visited [ str [ j ] ] == 0 ) { count ++ ; visited [ str [ j ] ] = 1 ; } sub_str += str [ j ] ; if ( count == dist_count ) break ; } if ( sub_str . length ( ) < size && count == dist_count ) { res = sub_str ; size = res . length ( ) ; } } return res ; }