Make Number of Distinct Characters Equal Problem
#2531
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2531.
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].
Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.
Example 1:
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.
Example 2:
Input: word1 = "abcc", word2 = "aab"
Output: true
Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.
Example 3:
Input: word1 = "abcde", word2 = "fghij"
Output: true
Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.
Constraints:
1 <= word1.length, word2.length <= 10^5word1andword2consist of only lowercase English letters.
Solution
Approach: Counting + Enumeration
Count the letters of both words and the number of distinct letters, x for word1 and y for word2. Then try every pair of letters (c1, c2) with c1 present in word1 and c2 present in word2, as the swap would do:
- If
c1 == c2, nothing changes, so the swap works whenx == y. - Otherwise
word1loses a distinct letter ifc1occurs once there and gains one ifc2was absent, givingx - (cnt1[c1] == 1) + (cnt1[c2] == 0).word2is symmetric:y - (cnt2[c2] == 1) + (cnt2[c1] == 0). If the two are equal, returntrue.
If no pair works, return false.
Complexity: O(m + n + 26^2) time and O(26) space, where m and n are the word lengths.
from collections import Counter
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