Check if all characters of a string can be made equal by increments or decrements
Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to make all characters of the string S equal by incrementing and decrementing any two characters from the given string by 1. If it is possible to make all the characters the same, then print “Yes”. Otherwise, print “No”.
Incrementing or decrementing any character means that change the characters to its next or previous character in the English alphabet respectively. If the characters are ‘a’ and ‘z’ then they cannot be changed further.
Input: S = “beb”
The characters of the given string S can be made equal by performing the below operations:
- For string “beb” increment ‘b’ by 1 and decrement ‘e’ by 1, then the string becomes “cdb”.
- For string “cdb” decrement ‘d’ by 1 and increment ‘b’ by 1, then the string becomes “ccc”.
Input: S = “geeks”
Approach: The given problem can be solved based on the below observations:
- While incrementing and decrementing any character by 1 at the same time, the sum of ASCII values of the string remains the same before and after the operation.
- Let suppose the ASCII value of any character is X. If all the characters are equal then the sum ASCII value of the string is N*X. Hence, it can be said that the sum is divisible by N. Therefore, the initial sum of the ASCII value needs to be divisible by N in order to make all the characters equal.
Follow the below steps to solve this problem:
- Initialize a variable sum, that stores the sum of the ASCII value of the given string.
- Traverse the given string S and for each character S[i] add the value of (S[i] – ‘a’ + 1) to the sum.
- After completing the above steps, if the value of sum is divisible by N then all the characters of the given string can be made equal. Therefore, print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.