Count pairs of characters in a string whose ASCII value difference is K - GeeksforGeeks

17 May, 2021
Given string str of lower case alphabets and a non-negative integer K. The task is to find the number of pairs of characters in the given string whose ASCII value difference is exactly K. Examples:  
Input: str = “abcdab”, K = 0 Output: 2 (a, a) and (b, b) are the only valid pairs.Input: str = “geeksforgeeks”, K = 1 Output: 8 (e, f), (e, f), (f, e), (f, e), (g, f), (f, g), (s, r) and (r, s) are the valid pairs.  
 
Approach: Store the frequency of each character in an array. Traverse through this frequency array to get the required answer. There exist two cases:  
If K = 0 then check if the similar character appears more than once i.e. if freq[i] > 1. If yes then add (freq[i] * (freq[i] – 1)) / 2 to the count.If K != 0 then check if there exist two characters with ASCII value difference as K say freq[i] and freq[j]. Then add freq[i] * freq[j] to the count.
If K = 0 then check if the similar character appears more than once i.e. if freq[i] > 1. If yes then add (freq[i] * (freq[i] – 1)) / 2 to the count.
If K != 0 then check if there exist two characters with ASCII value difference as K say freq[i] and freq[j]. Then add freq[i] * freq[j] to the count.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 26 // Function to return the count of// required pairs of charactersint countPairs(string str, int k){     // Length of the string    int n = str.size();     // To store the frequency    // of each character    int freq[MAX];    memset(freq, 0, sizeof freq);     // Update the frequency    // of each character    for (int i = 0; i < n; i++)        freq[str[i] - 'a']++;     // To store the required    // count of pairs    int cnt = 0;     // If ascii value difference is zero    if (k == 0) {         // If there exists similar characters        // more than once        for (int i = 0; i < MAX; i++)            if (freq[i] > 1)                cnt += ((freq[i] * (freq[i] - 1)) / 2);    }    else {         // If there exits characters with        // ASCII value difference as k        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 the required count    return cnt;} // Driver codeint main(){    string str = "abcdab";    int k = 0;     cout << countPairs(str, k);     return 0;}
// Java implementation of the approachimport java.util.Arrays; class GFG{     static int MAX = 26;     // Function to return the count of    // required pairs of characters    static int countPairs(char[] str, int k)    {         // Length of the string        int n = str.length;         // To store the frequency        // of each character        int[] freq = new int[MAX];         // Update the frequency        // of each character        for (int i = 0; i < n; i++)        {            freq[str[i] - 'a']++;        }         // To store the required        // count of pairs        int cnt = 0;         // If ascii value difference is zero        if (k == 0)        {             // If there exists similar characters            // more than once            for (int i = 0; i < MAX; i++)            {                if (freq[i] > 1)                {                    cnt += ((freq[i] * (freq[i] - 1)) / 2);                }            }        }        else        {             // If there exits characters with            // ASCII value difference as k            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 the required count        return cnt;    }     // Driver code    public static void main(String[] args)    {        String str = "abcdab";        int k = 0;         System.out.println(countPairs(str.toCharArray(), k));    }} /* This code contributed by PrinciRaj1992 */
# Python3 implementation of the approachMAX = 26 # Function to return the count of# required pairs of charactersdef countPairs(string, k) :     # Length of the string    n = len(string);     # To store the frequency    # of each character    freq = [0] * MAX;     # Update the frequency    # of each character    for i in range(n) :        freq[ord(string[i]) -             ord('a')] += 1;     # To store the required    # count of pairs    cnt = 0;     # If ascii value difference is zero    if (k == 0) :         # If there exists similar characters        # more than once        for i in range(MAX) :            if (freq[i] > 1) :                cnt += ((freq[i] *                        (freq[i] - 1)) // 2);         else :         # If there exits characters with        # ASCII value difference as k        for i in range(MAX) :            if (freq[i] > 0 and                i + k < MAX and                freq[i + k] > 0) :                cnt += (freq[i] * freq[i + k]);     # Return the required count    return cnt; # Driver codeif __name__ == "__main__" :     string = "abcdab";    k = 0;     print(countPairs(string, k));     # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;     class GFG{     static int MAX = 26;     // Function to return the count of    // required pairs of characters    static int countPairs(char[] str, int k)    {         // Length of the string        int n = str.Length;         // To store the frequency        // of each character        int[] freq = new int[MAX];         // Update the frequency        // of each character        for (int i = 0; i < n; i++)        {            freq[str[i] - 'a']++;        }         // To store the required        // count of pairs        int cnt = 0;         // If ascii value difference is zero        if (k == 0)        {             // If there exists similar characters            // more than once            for (int i = 0; i < MAX; i++)            {                if (freq[i] > 1)                {                    cnt += ((freq[i] * (freq[i] - 1)) / 2);                }            }        }        else        {             // If there exits characters with            // ASCII value difference as k            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 the required count        return cnt;    }     // Driver code    public static void Main(String[] args)    {        String str = "abcdab";        int k = 0;         Console.WriteLine(countPairs(str.ToCharArray(), k));    }} // This code has been contributed by 29AjayKumar
<script>       // JavaScript implementation of the approach      const MAX = 26;       // Function to return the count of      // required pairs of characters      function countPairs(str, k) {        // Length of the string        var n = str.length;         // To store the frequency        // of each character        var freq = new Array(MAX).fill(0);         // Update the frequency        // of each character        for (var i = 0; i < n; i++) {          freq[str[i].charCodeAt(0) -          "a".charCodeAt(0)]++;        }         // To store the required        // count of pairs        var cnt = 0;         // If ascii value difference is zero        if (k === 0) {          // If there exists similar characters          // more than once          for (var i = 0; i < MAX; i++) {            if (freq[i] > 1) {              cnt += (freq[i] * (freq[i] - 1)) / 2;            }          }        } else {          // If there exits characters with          // ASCII value difference as k          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 the required count        return cnt;      }       // Driver code      var str = "abcdab";      var k = 0;       document.write(countPairs(str.split(""), k));       </script>
2
 
ankthon
princiraj1992
29AjayKumar
rdtank
ASCII
Arrays
Mathematical
Strings
Arrays
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers