Skip to content

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<int> count(26);

    for (const char c : word)
      ++count[c - 'a'];

    // Try to remove each letter, then check if the frequency of all the letters
    // in `word` are equal.
    for (const char c : word) {
      --count[c - 'a'];
      if (equalFreq(count))
        return true;
      ++count[c - 'a'];
    }

    return false;
  }

 private:
  static constexpr int kMax = 101;

  bool equalFreq(const vector<int>& count) {
    int minfreq = kMax;
    int maxfreq = 0;
    for (const int freq : count)
      if (freq > 0) {
        minfreq = min(minfreq, freq);
        maxfreq = max(maxfreq, freq);
      }
    return minfreq == maxfreq;
  }
};
 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 the letters
    // in `word` are equal.
    for (final char c : word.toCharArray()) {
      --count[c - 'a'];
      if (equalFreq(count))
        return true;
      ++count[c - 'a'];
    }

    return false;
  }

  private static final int kMax = 101;

  private boolean equalFreq(int[] count) {
    int minfreq = kMax;
    int maxfreq = 0;
    for (final int freq : count)
      if (freq > 0) {
        minfreq = Math.min(minfreq, freq);
        maxfreq = Math.max(maxfreq, freq);
      }
    return minfreq == maxfreq;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def equalFrequency(self, word: str) -> bool:
    count = collections.Counter(word)

    # Try to remove each letter, then check if the frequency of all the letters
    # in `word` are equal.
    for c in word:
      count[c] -= 1
      if count[c] == 0:
        del count[c]
      if min(count.values()) == max(count.values()):
        return True
      count[c] += 1

    return False