Given a 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.
Input: str = “abcdab”, K = 0
(a, a) and (b, b) are the only valid pairs.
Input: str = “geeksforgeeks”, K = 1
(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.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count characters in a string whose ASCII values are prime
- Average of ASCII values of characters of a given string
- Program to find the XOR of ASCII values of characters in a string
- Program to find the product of ASCII values of characters in a string
- Program to find the largest and smallest ASCII valued characters in a string
- Count of ungrouped characters after dividing a string into K groups of distinct characters
- Binary string with given frequencies of sums of consecutive pairs of characters
- Number of ways to insert two pairs of parentheses into a string of N characters
- Count of times second string can be formed from the characters of first string
- Count of strings where adjacent characters are of difference one
- Count of pairs with difference at most K with no element repeating
- Count all distinct pairs with difference equal to k
- Count pairs in an array such that the absolute difference between them is ≥ K
- Count the pairs in an array such that the difference between them and their indices is equal
- Count pairs in an array whose absolute difference is divisible by K
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.