[LeetCode] Remove Letter To Equalize Frequency

2423. Remove Letter To Equalize Frequency

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 x is the number of times it occurs in the string.
  • You must remove exactly one letter and cannot choose to do nothing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool equalFrequency(string word) {
unordered_map<char,int> freq;
for(auto& ch : word) freq[ch]++;
for(auto& [k,v] : freq) {
--v;
int ma = 0, ok = true;
for(auto& [k,v] : freq) {
if(ma == 0) ma = v;
else if(v and ma != v) ok = false;
}
if(ok) return true;
v++;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/16/PS/LeetCode/remove-letter-to-equalize-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.