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
Make Distinct Character Counts Equalword1: "ac"2 distinctword2: "b"1 distinctswap"bc"2 distinct"a"1 distinctcheck2 ≠ 1Try otherswaps...Goal: Find any single swap that makes distinct counts equalEventually find valid swap → return trueKey: Calculate count changes without reconstructing strings
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
Asked in
Meta 8 Amazon 5
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen