Count all distinct characters .
int dist_count = 0 ; HashMap < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( str . charAt ( i ) ) ) { Integer a = mp . get ( str . charAt ( i ) ) ; mp . put ( str . charAt ( i ) , a + 1 ) ; } else { mp . put ( str . charAt ( i ) , 1 ) ; } } dist_count = mp . size ( ) ; int size = Integer . MAX_VALUE ; String res = " " ;