Count of ungrouped characters after dividing a string into K groups of distinct characters | Java code to implement the above approach ; Create array where index represents alphabets ; Fill count of every alphabet to corresponding array index ; Count for every element how much is exceeding from no . of groups then sum them ; Print answer ; Driver code
import java . util . * ; class GFG { static void findUngroupedElement ( String s , int k ) { int n = s . length ( ) ; int [ ] b = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) b [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { char p = s . charAt ( i ) ; b [ p - ' a ' ] += 1 ; } int sum = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( b [ i ] > k ) sum += b [ i ] - k ; } System . out . println ( sum ) ; } public static void main ( String srgs [ ] ) { String s = " stayinghomesaveslife " ; int k = 1 ; findUngroupedElement ( s , k ) ; } }