Given a string of lowercase alphabets, the task is to determine whether it is possible to remove at most one character so that the frequency of every distinct character becomes the same.
Examples:
Input : "xyyz"
Output : Yes
Explanation: Remove one 'y', frequencies become {'x':1, 'y':1, 'z':1}
Input: "xxxxyyzz"
Output: No
Explanation: It’s not possible to make all character frequencies equal by removing only one character.
Approach:
1. Count frequencies of all characters using Counter(). This gives a dictionary where keys are characters and values are their frequencies.
2. Extract frequency values and convert them into a set. A set removes duplicates, helping identify distinct frequencies.
3. Check conditions:
- If the set size is 1, all characters already have the same frequency: print "Yes".
- If the set size is 2, check if the difference between the two frequencies is 1: "Yes" (removal possible).
- Otherwise, print "No".
Python Implementation:
from collections import Counter
s = 'xxxyyzzt'
freq = Counter(s)
same = list(set(freq.values()))
if len(same) > 2:
print('No')
elif len(same) == 2 and abs(same[1] - same[0]) > 1:
print('No')
else:
print('Yes')
Output
No
Explanation:
- Counter(s): counts frequency of each character.
- set(freq.values()): extracts unique frequency counts.
- Final conditions check if the string can be made uniform by removing one character.