Count pairs of characters in a string whose ASCII value difference is K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  26 NEW_LINE int countPairs ( string str , int k ) { int n = str . size ( ) ; int freq [ MAX ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < n ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; int cnt = 0 ; if ( k == 0 ) { for ( int i = 0 ; i < MAX ; i ++ ) if ( freq [ i ] > 1 ) cnt += ( ( freq [ i ] * ( freq [ i ] - 1 ) ) / 2 ) ; } else { for ( int i = 0 ; i < MAX ; i ++ ) if ( freq [ i ] > 0 && i + k < MAX && freq [ i + k ] > 0 ) cnt += ( freq [ i ] * freq [ i + k ] ) ; ; } return cnt ; } int main ( ) { string str = " abcdab " ; int k = 0 ; cout << countPairs ( str , k ) ; return 0 ; }