Make Number of Distinct Characters Equal - 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].
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.
Input & Output
Example 1 — Basic Case
$
Input:
word1 = "ac", word2 = "b"
›
Output:
true
💡 Note:
Swap 'c' in word1 with 'b' in word2. Result: word1 = "ab" (2 distinct), word2 = "c" (1 distinct). Since 2 ≠ 1, try swapping 'a' with 'b': word1 = "bc" (2 distinct), word2 = "a" (1 distinct). Still not equal. Actually, swapping 'a' with 'b' gives word1 = "bc", word2 = "a", but we need to check all possibilities systematically.
Example 2 — Already Equal
$
Input:
word1 = "ab", word2 = "cd"
›
Output:
false
💡 Note:
word1 has 2 distinct characters, word2 has 2 distinct characters. They're already equal, but we need exactly one swap. Any single swap will change the counts, so it's impossible to maintain equality with exactly one move.
Example 3 — Large Difference
$
Input:
word1 = "abcc", word2 = "aab"
›
Output:
true
💡 Note:
word1 has 3 distinct characters {a,b,c}, word2 has 2 distinct characters {a,b}. We can swap one 'c' from word1 with 'a' from word2, making both have the same distinct count.
Constraints
- 1 ≤ word1.length, word2.length ≤ 100
- word1 and word2 consist of lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Count distinct characters in each string
2
Swap Simulation
Test character swaps to balance counts
3
Result
Return true if any swap achieves equality
Key Takeaway
🎯 Key Insight: Use frequency maps to efficiently calculate distinct count changes for each possible character swap
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code