Count of ungrouped characters after dividing a string into K groups of distinct characters | Python3 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
def findUngroupedElement ( s , k ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE b = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT p = s [ i ] NEW_LINE b [ ord ( p ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT sum = 0 ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( b [ i ] > k ) : NEW_LINE INDENT sum += b [ i ] - k NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT s = " stayinghomesaveslife " NEW_LINE k = 1 NEW_LINE findUngroupedElement ( s , k ) NEW_LINE