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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count characters in a string whose ASCII values are prime
- Convert all lowercase characters to uppercase whose ASCII value is co-prime with k
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
- Convert Hexadecimal value String to ASCII value String
- Replace every character of string by character whose ASCII value is K times more than it
- Sub-strings having exactly k characters that have ASCII value greater than p
- Total character pairs from two strings, with equal number of set bits in their ascii value
- Count of alphabets whose ASCII values can be formed with the digits of N
- Program to find the largest and smallest ASCII valued characters in a string
- 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 XOR of ASCII values of characters in a string
- Count of alphabets having ASCII value less than and greater than k
- Count and Print the alphabets having ASCII value in the range [l, r]
- Count and Print the alphabets having ASCII value not in the range [l, r]
- Convert the ASCII value sentence to its equivalent string
- Find the sum of the ascii values of characters which are present at prime positions
- Count pairs from two sorted arrays whose sum is equal to a given value x
- Decode an Encoded Base 64 String to ASCII String
- Program to print ASCII Value of a character
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.