#2531

Make Number of Distinct Characters Equal

expert · 1155 · lc medium +32 · premium · verified · 27.5% accepted · 609 likes · top 5%

Description

Given two 0-indexed strings word1 and word2, a single move lets you choose an index i in word1 and an index j in word2 and swap word1[i] with word2[j]. Return true if exactly one such move can make the count of distinct characters in word1 equal to the count in word2, or 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.

Code

1
2
3