Leetcode 1941. Check if All Characters Have Equal Number of Occurrences
You are given a string s
consisting of lowercase English letters. Your task is to determine if all characters in the string have the same number of occurrences.
Return true
if all characters have the same frequency, and false
otherwise.
true
; otherwise, return false
.Here’s the implementation in C++:
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
bool areOccurrencesEqual(std::string s) {
// Step 1: Count the frequency of each character
std::unordered_map<char, int> frequency;
for (char c : s) {
frequency[c]++;
}
// Step 2: Check if all characters have the same frequency
std::unordered_set<int> uniqueFrequencies;
for (const auto& pair : frequency) {
uniqueFrequencies.insert(pair.second);
}
// If there is exactly one unique frequency, return true
return uniqueFrequencies.size() == 1;
}
int main() {
std::string s = "abacbc";
if (areOccurrencesEqual(s)) {
std::cout << "True" << std::endl;
} else {
std::cout << "False" << std::endl;
}
return 0;
}
The solution involves two main steps:
Overall, the time complexity of the solution is (O(n)), where (n) is the length of the string s
. The space complexity is (O(1)) for the fixed set of lowercase letters.
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?