Check if a string has all characters with same frequency with one variation allowed | Assuming only lower case characters ; To check a string S can be converted to a valid string by removing less than or equal to one character . ; freq [ ] : stores the frequency of each character of a string ; Find first character with non - zero frequency ; Find a character with frequency different from freq1 . ; If we find a third non - zero frequency or count of both frequencies become more than 1 , then return false ; If we find a third non - zero freq ; If counts of both frequencies is more than 1 ; Return true if we reach here ; Driver code
CHARS = 26 NEW_LINE def isValidString ( str ) : NEW_LINE INDENT freq = [ 0 ] * CHARS NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT freq1 = 0 NEW_LINE count_freq1 = 0 NEW_LINE for i in range ( CHARS ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT freq1 = freq [ i ] NEW_LINE count_freq1 = 1 NEW_LINE break NEW_LINE DEDENT DEDENT freq2 = 0 NEW_LINE count_freq2 = 0 NEW_LINE for j in range ( i + 1 , CHARS ) : NEW_LINE INDENT if ( freq [ j ] != 0 ) : NEW_LINE INDENT if ( freq [ j ] == freq1 ) : NEW_LINE INDENT count_freq1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_freq2 = 1 NEW_LINE freq2 = freq [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT for k in range ( j + 1 , CHARS ) : NEW_LINE INDENT if ( freq [ k ] != 0 ) : NEW_LINE INDENT if ( freq [ k ] == freq1 ) : NEW_LINE INDENT count_freq1 += 1 NEW_LINE DEDENT if ( freq [ k ] == freq2 ) : NEW_LINE INDENT count_freq2 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( count_freq1 > 1 and count_freq2 > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abcbc " NEW_LINE if ( isValidString ( str ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT