Make Number of Distinct Characters Equal - Problem

You are given two strings word1 and word2. Your goal is to equalize the number of distinct characters in both strings using exactly one character swap between them.

A move consists of choosing any character at position i in word1 and any character at position j in word2, then swapping them. You must determine if it's possible to make both strings have the same number of unique characters with exactly one such swap.

Example: If word1 = "ac" has 2 distinct characters and word2 = "b" has 1 distinct character, can we swap one character to make them equal?

Return true if such a swap exists, false otherwise.

Input & Output

example_1.py โ€” Basic case
$ Input: word1 = "ac", word2 = "b"
โ€บ Output: false
๐Ÿ’ก Note: No matter which characters we swap, we can't make both strings have the same number of distinct characters. Initially: word1 has 2 distinct, word2 has 1 distinct.
example_2.py โ€” Successful swap
$ Input: word1 = "abcc", word2 = "aab"
โ€บ Output: true
๐Ÿ’ก Note: We can swap the 'c' from word1 with 'a' from word2. After swap: word1 becomes "abca" (3 distinct: a,b,c), word2 becomes "cab" (3 distinct: a,b,c).
example_3.py โ€” Already equal
$ Input: word1 = "abc", word2 = "def"
โ€บ Output: true
๐Ÿ’ก Note: Both strings already have 3 distinct characters. Any swap maintains this equality (though the specific characters change).

Visualization

Tap to expand
Collection 1AAB2 unique typesCollection 2CCC1 unique typeTrade A โ†” CResultCollection 1: A,B,C โ†’ 3 typesCollection 2: C,C,A โ†’ 2 typesStill unequal!
Understanding the Visualization
1
Count Your Cards
First, count how many of each type you have in both collections
2
Analyze Trade Impact
For each possible trade, predict how it affects unique card counts
3
Find Valid Trade
Look for any trade that equalizes the unique card counts
4
Make Decision
Return true if such a trade exists, false otherwise
Key Takeaway
๐ŸŽฏ Key Insight: Instead of trying every possible trade, we can mathematically predict the outcome by analyzing character frequencies and the four possible swap scenarios.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n + m)

Single pass to count frequencies, then O(1) analysis for each unique character pair

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Fixed size arrays for character frequencies (26 letters max)

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค word1.length, word2.length โ‰ค 105
  • word1 and word2 consist only of lowercase English letters
  • Exactly one swap must be performed
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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