algoadvance

Leetcode 1897. Redistribute Characters to Make All Strings Equal

Problem Statement

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.

Clarifying Questions

Strategy

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:

  1. Count the total frequency of each character in the entire list of words.
  2. For each character count, check if it can be evenly divided by the number of words.
    • This ensures that each character can be evenly distributed across all words.

Code

#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;
}

Time Complexity

Overall, the time complexity is O(N * M). This should be efficient given the constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI