You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.
Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.
Note:
- The frequency of a letter
xis the number of times it occurs in the string. - You must remove exactly one letter and cannot chose to do nothing.
Example 1:
Input: word = "abcc" Output: true Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.
Example 2:
Input: word = "aazz" Output: false Explanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.
Constraints:
2 <= word.length <= 100wordconsists of lowercase English letters only.
Companies: tcs
Related Topics:
Hash Table, String, Counting
Similar Questions:
- only one unique character
- one frequency = 1, and others are of the same frequency
- one freq =
n+1, and all other characters has frequency =n.
// OJ: https://leetcode.com/problems/remove-letter-to-equalize-frequency
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
bool equalFrequency(string s) {
int cnt[26] = {};
for (char c : s) cnt[c - 'a']++;
map<int, int> freq;
for (int n : cnt) {
if (n) freq[n]++;
}
return (freq.size() == 1 && freq.begin()->second == 1)
|| (freq.begin()->first == 1 && ((freq.begin()->second == 1 && freq.size() == 2) || freq.size() == 1))
|| (freq.begin()->first + 1 == freq.rbegin()->first && freq.rbegin()->second == 1);
}
};