Count of ungrouped characters after dividing a string into K groups of distinct characters | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findUngroupedElement ( string s , int k ) { int n = s . length ( ) ; int b [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) b [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { char p = s . at ( i ) ; b [ p - ' a ' ] += 1 ; } int sum = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( b [ i ] > k ) sum += b [ i ] - k ; } cout << sum << endl ; } int main ( ) { string s = " stayinghomesaveslife " ; int k = 1 ; findUngroupedElement ( s , k ) ; return 0 ; }