2423. Remove Letter To Equalize Frequency

• Time: $O(26n) = O(n)$
• Space: $O(26) = O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Solution { public: bool equalFrequency(string word) { vector count(26); for (const char c : word) ++count[c - 'a']; // Try to remove each letter, then check if the frequency of all letters in // word are equal for (const char c : word) { --count[c - 'a']; if (equalCount(count)) return true; ++count[c - 'a']; } return false; } private: bool equalCount(const vector& count) { int freq = -1; for (const int c : count) { if (c == 0 || c == freq) continue; if (freq == -1) freq = c; else return false; } return true; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 class Solution { public boolean equalFrequency(String word) { int[] count = new int[26]; for (final char c : word.toCharArray()) ++count[c - 'a']; // Try to remove each letter, then check if the frequency of all letters in // word are equal for (final char c : word.toCharArray()) { --count[c - 'a']; if (equalCount(count)) return true; ++count[c - 'a']; } return false; } private boolean equalCount(int[] count) { int freq = -1; for (final int c : count) { if (c == 0 || c == freq) continue; if (freq == -1) freq = c; else return false; } return true; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution: def equalFrequency(self, word: str) -> bool: count = collections.Counter(word) # Try to remove each letter, then check if the frequency of all letters in # word are equal for c in word: count[c] -= 1 if self._equalCount(count): return True count[c] += 1 return False def _equalCount(self, count: Dict[int, int]) -> bool: freq = -1 for c in count.values(): if c == 0 or c == freq: continue if freq == -1: freq = c else: return False return True