Leetcode 2423. Remove Letter To Equalize Frequency
Given a string word
, you have to remove exactly one character from the string so that the frequency of each character in the string becomes the same. Return true
if it’s possible to achieve that, or false
otherwise.
Example 1:
Input: word = "abcc"
Output: true
Explanation: Removing 'c' from "abcc" will make the frequency of 'a' and 'b' both 1.
Example 2:
Input: word = "aazz"
Output: false
word
will have a length in the range [2, 10^5].word
contain?
To solve this problem, follow these steps:
Here’s a more detailed breakdown:
1
and should appear exactly once. Removing a character with this frequency will balance the string.1
, removing any one character from the higher frequency group should balance the string.#include <iostream>
#include <unordered_map>
#include <string>
#include <cmath>
bool equalFrequency(std::string word) {
std::unordered_map<char, int> charFreq;
for (char c : word) {
charFreq[c]++;
}
std::unordered_map<int, int> freqCount;
for (auto& cf : charFreq) {
freqCount[cf.second]++;
}
if (freqCount.size() == 1) {
// All characters already have the same frequency or all except one
return true;
} else if (freqCount.size() == 2) {
// There are exactly two different frequencies
auto it1 = freqCount.begin();
auto it2 = it1;
++it2;
// Ensure that the first frequency is the smaller one
if (it1->first > it2->first) {
std::swap(it1, it2);
}
// Now it1 is the smaller frequency
if (it1->first == 1 && it1->second == 1) {
// Case where there's exactly one character with frequency 1
return true;
}
if (it2->first == it1->first + 1 && it2->second == 1) {
// Case where removing one character from the higher frequency
return true;
}
}
return false;
}
int main() {
std::string word1 = "abcc";
std::string word2 = "aazz";
std::cout << std::boolalpha << equalFrequency(word1) << std::endl; // true
std::cout << std::boolalpha << equalFrequency(word2) << std::endl; // false
return 0;
}
The time complexity of the solution is (O(n)), where (n) is the length of the input string.
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?