Leetcode 2423. Remove Letter To Equalize Frequency
Given a string s
, you are allowed to remove one character from the string. Your task is to determine if you can remove exactly one character so that the frequency of every distinct character in the string is the same.
false
.true
.Depending on the number of unique frequencies, check the conditions under which a single deletion might equalize them.
true
.import java.util.HashMap;
import java.util.HashSet;
public class Solution {
public boolean equalFrequency(String s) {
// Step 1: Calculate character frequencies
HashMap<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// Step 2: Calculate frequencies of those frequencies
HashMap<Integer, Integer> freqCountMap = new HashMap<>();
for (int freq : frequencyMap.values()) {
freqCountMap.put(freq, freqCountMap.getOrDefault(freq, 0) + 1);
}
// Step 3: Analyze the frequency counts
if (freqCountMap.size() == 1) {
// All characters have the same frequency
return true;
} else if (freqCountMap.size() == 2) {
// Two distinct frequencies
int[] keys = new int[2];
int[] values = new int[2];
int i = 0;
for (int key : freqCountMap.keySet()) {
keys[i] = key;
values[i] = freqCountMap.get(key);
i++;
}
int freq1 = keys[0], count1 = values[0];
int freq2 = keys[1], count2 = values[1];
// Case 1: One frequency is 1 and its count is 1
if ((freq1 == 1 && count1 == 1) || (freq2 == 1 && count2 == 1)) {
return true;
}
// Case 2: Difference between frequencies is 1 and higher frequency count is 1
if ((freq1 == freq2 + 1 && count1 == 1) || (freq2 == freq1 + 1 && count2 == 1)) {
return true;
}
}
// In all other cases, it's not possible to equalize the frequencies by removing one letter
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.equalFrequency("abcc")); // Output: true
System.out.println(sol.equalFrequency("aazz")); // Output: false
}
}
s
only contains lowercase letters).In this approach, the most time-consuming part is traversing the string to compute frequencies, which is linear relative to the size of the string. Hence, the solution is efficient for the given constraint (1 ≤ s.length
≤ 100,000).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?