2423. Remove Letter To Equalize Frequency
Description
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.
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 <= 100
word
consists of lowercase English letters only.
Solutions
Solution 1: Counting + Enumeration
First, we use a hash table or an array of length $26$ named $cnt$ to count the number of occurrences of each letter in the string.
Next, we enumerate the $26$ letters. If letter $c$ appears in the string, we decrement its count by one, then check whether the counts of the remaining letters are the same. If they are, return true
. Otherwise, increment the count of $c$ by one and continue to enumerate the next letter.
If the enumeration ends, it means that it is impossible to make the counts of the remaining letters the same by deleting one letter, so return false
.
The time complexity is $O(n + C^2)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $word$, and $C$ is the size of the character set. In this problem, $C = 26$.
1 2 3 4 5 6 7 8 9 |
|
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 |
|
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 |
|
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 |
|
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 |
|