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