Make Number of Distinct Characters Equal — LeetCode 2531 Python Solution

MediumHash TableStringCounting
Problem
#2531
Pattern
Hash Map
Reading time
3 min

The problem

You are given two 0-indexed strings word1 and word2. A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j].

Example

Input
word1 = "ac", word2 = "b"
Output
false
Explanation
Any pair of swaps would yield two distinct characters in the first string, and one in the second string.

Python solution

Python
class Solution:
    def isItPossible(self, word1: str, word2: str) -> bool:
        cnt1 = Counter(word1)
        cnt2 = Counter(word2)
        x, y = len(cnt1), len(cnt2)
        for c1, v1 in cnt1.items():
            for c2, v2 in cnt2.items():
                if c1 == c2:
                    if x == y:
                        return True
                else:
                    a = x - (v1 == 1) + (cnt1[c2] == 0)
                    b = y - (v2 == 1) + (cnt2[c1] == 0)
                    if a == b:
                        return True
        return False

Complexity

MeasureComplexity
TimeO(m + n + |\Sigma|^2), where m and n are the lengths of the strings \textit{word1} and \textit{word2}, and \Sigma is the character set
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2531. Make Number of Distinct Characters 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 2531. Make Number of Distinct Characters Equal?
LeetCode 2531. Make Number of Distinct Characters Equal is rated Medium on LeetCode.
What is the time complexity of LeetCode 2531. Make Number of Distinct Characters Equal?
The Python solution on this page runs in O(m + n + |\Sigma|^2), where m and n are the lengths of the strings \textit{word1} and \textit{word2}, and \Sigma is the character set.
What is the space complexity of LeetCode 2531. Make Number of Distinct Characters Equal?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2531. Make Number of Distinct Characters Equal cover?
LeetCode 2531. Make Number of Distinct Characters 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