Count of ungrouped characters after dividing a string into K groups of distinct characters | Javascript implementation of 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
function findUngroupedElement ( s , k ) { let n = s . length ; let b = Array . from ( { length : 26 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < 26 ; i ++ ) b [ i ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let p = s [ i ] ; b [ p . charCodeAt ( ) - ' ' . charCodeAt ( ) ] += 1 ; } let sum = 0 ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( b [ i ] > k ) sum += b [ i ] - k ; } document . write ( sum ) ; } let s = " " ; let k = 1 ; findUngroupedElement ( s , k ) ;