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: false
💡 Note: word1 = "ac" has 2 distinct characters {a,c}, word2 = "b" has 1 distinct character {b}. Swapping 'a' with 'b' gives word1 = "bc" (2 distinct) and word2 = "a" (1 distinct). Swapping 'c' with 'b' gives word1 = "ab" (2 distinct) and word2 = "c" (1 distinct). No single swap can make both words have equal distinct character counts.
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 Number of Distinct Characters Equal INPUT word1 = "ac" a c i=0 i=1 word2 = "b" b j=0 Distinct Characters: set1: {a,c} set2: {b} |set1|=2, |set2|=1 Not equal! ALGORITHM STEPS 1 Build character sets Count freq in both words 2 Try all swap pairs For each char c1 in set1 For each char c2 in set2 3 Simulate swap Calculate new set sizes 4 Check equality If sizes match, return true Try: swap 'a' with 'b' word1: "ac" --> "bc" word2: "b" --> "a" new set1: {b,c} size=2 new set2: {a} size=1 FINAL RESULT Successful Swap Found! BEFORE: "ac" (2) "b" (1) swap i=0 (a) with j=0 (b) AFTER: "bc" (2) "a" (1) Try: swap 'c' with 'b' "ab" (2) "c" (1) Output: true Key Insight: Use sets to track distinct characters. For each possible swap pair (c1, c2), calculate the change in distinct count: +1 if char is new, -1 if char becomes absent, 0 otherwise. Check if final distinct counts are equal. Time: O(n + 26*26) where n = total length of both strings. TutorialsPoint - Make Number of Distinct Characters Equal | Set-Based Optimization
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