Count pairs of characters in a string whose ASCII value difference is K | JavaScript 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
const MAX = 26 ; function countPairs ( str , k ) { var n = str . length ; var freq = new Array ( MAX ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { freq [ str [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } var cnt = 0 ; if ( k === 0 ) { for ( var i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] > 1 ) { cnt += ( freq [ i ] * ( freq [ i ] - 1 ) ) / 2 ; } } } else { for ( var i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] > 0 && i + k < MAX && freq [ i + k ] > 0 ) { cnt += freq [ i ] * freq [ i + k ] ; } } } return cnt ; } var str = " " ; var k = 0 ; document . write ( countPairs ( str . split ( " " ) , k ) ) ;