Count pairs of characters in a string whose ASCII value difference is K | Python3 implementation of the approach ; Function to return the count of required pairs of characters ; Length of the string ; To store the frequency of each character ; Update the frequency of each character ; To store the required count of pairs ; If ascii value difference is zero ; If there exists similar characters more than once ; If there exits characters with ASCII value difference as k ; Return the required count ; Driver code
MAX = 26 NEW_LINE def countPairs ( string , k ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE if ( k == 0 ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] > 1 ) : NEW_LINE INDENT cnt += ( ( freq [ i ] * ( freq [ i ] - 1 ) ) // 2 ) ; NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] > 0 and i + k < MAX and freq [ i + k ] > 0 ) : NEW_LINE INDENT cnt += ( freq [ i ] * freq [ i + k ] ) ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdab " ; NEW_LINE k = 0 ; NEW_LINE print ( countPairs ( string , k ) ) ; NEW_LINE DEDENT