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
- Maximum length of balanced string after swapping and removal of characters
- Remove even frequency characters from the string
- String with frequency of characters in Lucas Sequence
- Minimum operations to make frequency of all characters equal K
- Character whose frequency is equal to the sum of frequencies of other characters of the given string
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- 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
- Check if the frequency of any character is more than half the length of the string
- Check whether two strings contain same characters in same order
- Check if both halves of the string have same set of characters
- Quick way to check if all the characters of a string are same