LeetCode 2423: Remove Letter To Equalize Frequency
Problem Description
Explanation
To solve this problem, we need to check if it's possible to remove one letter from the given word such that the frequency of all remaining letters becomes equal. We can approach this problem by iterating through the word and storing the frequency of each character. Then, we find the most common frequency and the least common frequency. If the difference between these frequencies is less than or equal to 1, we can remove one letter to make all frequencies equal.
-
Algorithm:
- Initialize a frequency map to store the count of each character in the word.
- Iterate through the word and update the frequency map.
- Find the maximum and minimum frequencies in the map.
- If the difference between the maximum and minimum frequencies is less than or equal to 1, return true; otherwise, return false.
-
Time Complexity: O(n), where n is the length of the input word.
-
Space Complexity: O(n) for storing the frequency map.
Solutions
class Solution {
public boolean canBeMadeEqual(String word) {
Map<Character, Integer> freqMap = new HashMap<>();
// Count frequencies of characters
for (char c : word.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
// Find maximum and minimum frequencies
int maxFreq = Collections.max(freqMap.values());
int minFreq = Collections.min(freqMap.values());
// Check if frequencies can be equalized by removing one letter
return maxFreq - minFreq <= 1;
}
}
Loading editor...