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 __trueif it is possible to remove one letter so that the frequency of all letters inwordare equal, andfalseotherwise.
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.
Input: word ="aazz"Output: falseExplanation: We must delete a character, so either the frequency of "a"is1 and the frequency of "z"is2, or vice versa. It is impossible to make all present letters have equal frequency.
import java.util.*;
publicclassSolution {
publicbooleanequalFrequency(String word) {
int[] freq =newint[26];
for (char c : word.toCharArray()) freq[c -'a']++;
for (int i = 0; i < 26; i++) {
if (freq[i]== 0) continue;
freq[i]--;
Set<Integer> s =new HashSet<>();
for (int f : freq) if (f > 0) s.add(f);
if (s.size() == 1) returntrue;
freq[i]++;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
funequalFrequency(word: String): Boolean {
val freq = IntArray(26)
for (c in word) freq[c - 'a']++for (i in0 until 26) {
if (freq[i] ==0) continue freq[i]--val s = mutableSetOf<Int>()
for (f in freq) if (f > 0) s.add(f)
if (s.size ==1) returntrue freq[i]++ }
returnfalse}
1
2
3
4
5
6
7
8
9
10
defequalFrequency(word: str) -> bool:
from collections import Counter
freq = Counter(word)
for ch in freq:
freq[ch] -=1 vals = [v for v in freq.values() if v >0]
if len(set(vals)) ==1:
returnTrue freq[ch] +=1returnFalse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::collections::HashMap;
fnequal_frequency(word: &str) -> bool {
letmut freq = HashMap::new();
for c in word.chars() {
*freq.entry(c).or_insert(0) +=1;
}
for (&ch, _) in freq.clone().iter() {
*freq.get_mut(&ch).unwrap() -=1;
let vals: Vec<_>= freq.values().filter(|&&v| v >0).collect();
let set: std::collections::HashSet<_>= vals.iter().cloned().collect();
if set.len() ==1 {
returntrue;
}
*freq.get_mut(&ch).unwrap() +=1;
}
false}
1
2
3
4
5
6
7
8
9
10
11
functionequalFrequency(word: string):boolean {
constfreq: Record<string, number> = {};
for (constcofword) freq[c] = (freq[c] ||0) +1;
for (constchinfreq) {
freq[ch]--;
constvals= Object.values(freq).filter(v=>v>0);
if (newSet(vals).size===1) returntrue;
freq[ch]++;
}
returnfalse;
}