Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.
Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str = “xyyzz” Output : Yes We can remove character ‘x’ from above string to make the frequency of each character same. Input : str = “xxxxyyzz” Output : No It is not possible to make frequency of each character same just by removing at most one character from above string.
Main thing to observe in this problem is that position of characters does not matter here so we will count the frequency of characters, if all of them are same then we are done and there is no need to remove any character to make frequency of characters same Otherwise we can iterate over all characters one by one and decrease their frequency by one, if all frequencies become same then we will flag that it is possible to make character frequency same by at most one removal and if frequencies doesn’t match then we will increase that frequency again and loop for other characters.
Time Complexity : O(n) assuming alphabet size is constant.
This article is contributed by Utkarsh Trivedi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program to check if all characters have even frequency
- Check if a string has all characters with same frequency with one variation allowed
- Check whether frequency of characters in a string makes Fibonacci Sequence
- Remove even frequency characters from the string
- String with frequency of characters in Lucas Sequence
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Check if the frequency of all the digits in a number is same
- Quick way to check if all the characters of a string are same
- Check if both halves of the string have same set of characters
- Check if lowercase and uppercase characters are in same order
- Check whether the frequencies of all the characters in a string are prime or not
- Program to check if first and the last characters of string are equal
- Check if the characters of a given string are in alphabetical order
- Check if both halves of the string have same set of characters in Python
- Check if characters of one string can be swapped to form other
Improved By : ChitraNayal