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:
- Count characters in a string whose ASCII values are prime
- Average of ASCII values of characters of a given 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
- Number of ways to insert two pairs of parentheses into a string of N characters
- Count of strings where adjacent characters are of difference one
- Count pairs in an array such that the absolute difference between them is ≥ K
- Count all distinct pairs with difference equal to k
- Count the pairs in an array such that the difference between them and their indices is equal
- Count the pairs of vowels in the given string
- Count equal pairs from given string arrays
- Count number of equal pairs in a string
- Count number of substrings of a string consisting of same characters
- Check whether count of distinct characters in a string is Prime or not
- Sub-strings having exactly k characters that have ASCII value greater than p
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.