Check if frequency of all characters can become same by one removal | Python3 program to get same frequency character string by removal of at most one char ; Utility method to get index of character ch in lower alphabet characters ; Returns true if all non - zero elements values are same ; get first non - zero element ; check equality of each element with variable same ; Returns true if we can make all character frequencies same ; fill frequency array ; if all frequencies are same , then return true ; Try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; Check character only if it occurs in str ; Driver code
M = 26 NEW_LINE def getIdx ( ch ) : NEW_LINE INDENT return ( ord ( ch ) - ord ( ' a ' ) ) NEW_LINE DEDENT def allSame ( freq , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT same = freq [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( freq [ j ] > 0 and freq [ j ] != same ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def possibleSameCharFreqByOneRemoval ( str1 ) : NEW_LINE INDENT l = len ( str1 ) NEW_LINE freq = [ 0 ] * M NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT freq [ getIdx ( str1 [ i ] ) ] += 1 NEW_LINE DEDENT if ( allSame ( freq , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT freq [ i ] -= 1 NEW_LINE if ( allSame ( freq , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT freq [ i ] += 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " xyyzz " NEW_LINE if ( possibleSameCharFreqByOneRemoval ( str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT