![]() |
VOOZH | about |
Given a string S having lowercase alphabets, the task is to check if all distinct characters in S occurs same number of times by removing 1 or 0 characters from it.
Examples :
Input : string str = "abbca"
Output : Yes
Explanation: We can make it valid by removing "c"Input : string str = "aabbcd"
Output : No
Explanation: We need to remove at least two characters to make it valid.Input : string str = "abbccd"
Output : No
Explanation: We are allowed to traverse string only once.
Use a frequency array that stores frequencies of all characters. Once we have frequencies of all characters in an array, we check if count of total different and non-zero values are not more than 2. Also, one of the counts of two allowed different frequencies must be less than or equal to 2.
Below is the implementation of the above approach:
YES
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no other extra space is required, so it is a constant.
Uses a hashmap to count character frequencies and verifies that there are at most two distinct characters with different frequencies.
Below is the implementation.
true
TimeComplexity: O(N), where N is the length of the given string.
AuxiliarySpace: O(N)