Leetcode 1897. Redistribute Characters to Make All Strings Equal
Given an array of strings words
, determine if it is possible to redistribute the characters in words
so that every string in words
is equal. All words must contain the exact same characters in the same quantities after redistribution.
words
contain?
To solve this problem, we need to check whether we can reorganize the characters such that every word becomes the same. Here is the approach:
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
bool makeEqual(vector<string>& words) {
unordered_map<char, int> charCount;
int numWords = words.size();
// Count the total occurrences of each character in all the words
for (const string& word : words) {
for (char ch : word) {
charCount[ch]++;
}
}
// Check if each character count is divisible by the number of words
for (const auto &entry : charCount) {
if (entry.second % numWords != 0) {
return false;
}
}
return true;
}
Overall, the time complexity is O(N * M). This should be efficient given the constraints.
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?