Redistribute Characters to Make All Strings Equal — LeetCode 1897 Python Solution

EasyHash TableStringCounting
Problem
#1897
Pattern
Hash Map
Reading time
2 min

The problem

You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].

Example

Input
words = ["abc","aabc","bc"]
Output
true
Explanation
Move the first 'a' in words[1] to the front of words[2],

Python solution

Python
class Solution:
    def makeEqual(self, words: List[str]) -> bool:
        cnt = Counter()
        for w in words:
            for c in w:
                cnt[c] += 1
        n = len(words)
        return all(v % n == 0 for v in cnt.values())

Complexity

MeasureComplexity
TimeO(L)
SpaceO(|\Sigma|) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1897. Redistribute Characters to Make All Strings Equal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1897. Redistribute Characters to Make All Strings Equal?
LeetCode 1897. Redistribute Characters to Make All Strings Equal is rated Easy on LeetCode.
What is the time complexity of LeetCode 1897. Redistribute Characters to Make All Strings Equal?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 1897. Redistribute Characters to Make All Strings Equal?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 1897. Redistribute Characters to Make All Strings Equal cover?
LeetCode 1897. Redistribute Characters to Make All Strings Equal is tagged Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview