
You are given ‘STR’ = “aabc”. The answer will be “Yes” because if we remove one ‘a’ from ‘STR,’ the frequency of each distinct character will be the same.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains a string denoting the given string.
For each test case, print “Yes” if it is possible to make the frequency of each distinct character the same by removing at most one character from ‘STR’, otherwise “No”.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= STR.LENGTH <= 5000
Time limit: 1 sec
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
We will solve this problem using the concept of hashing. In this problem, we are only concerned with the frequency of each character and not the position of the character. So, we will create a frequency count array to store the frequency of each character. Then, if all the frequencies are the same, we will return true. Otherwise, we will decrease the frequency of each character in ‘STR’ one by one and check if the frequency becomes the same or not. If the frequency becomes the same, we will return true. Otherwise, we will backtrack and increase the frequency of the current character and check the next character.
Algorithm:
Maintain a function ‘SAMEFREQUENCY(int[] FREQ)’: