Problem Description
Given two strings word1 and word2, you can perform exactly one move consisting of swapping one character from word1 with one character from word2. The goal is to check if it is possible to make the number of distinct characters in word1 and word2 equal after this one swap. The swap is allowed even if the characters being swapped are the same.
Key Insights
- Only one swap is allowed, so you must calculate the impact of a single swap on the count of distinct characters.
- Swapping two characters that are identical leaves both strings unchanged. Thus if the distinct counts are already equal, a swap of the same character (present in both strings) immediately gives a valid solution.
- For different characters a (from word1) and b (from word2), the swap may remove a from a string if it occurs only once and may add a new character if b wasn’t previously present (and vice-versa). Adjust the distinct count accordingly.
- Since the number of possible letters is limited to 26 (lowercase English letters), iterating over all possible pairs (a, b) is efficient.
Space and Time Complexity
Time Complexity: O(1) — since we iterate over at most 26*26 possible letter pairs. Space Complexity: O(1) — additional space is used only for fixed-size frequency dictionaries.
Solution
The solution involves these steps:
- Count the frequency of each character in word1 and word2.
- Calculate the number of distinct characters in both strings.
- Iterate over each letter a in word1 (present in its frequency dictionary) and each letter b in word2 (present in its frequency dictionary).
- If a == b and the current distinct counts are equal, a swap of the same character results in no change. Return true.
- If a != b, simulate the swap:
- For word1:
- If a appears only once, swapping it out will reduce the distinct count by 1.
- If b is not already in word1, swapping it in will increase the distinct count by 1.
- For word2:
- Similarly, adjust for losing b (if its count is 1) and adding a (if a is not already present).
- For word1:
- If the new distinct counts are equal, return true.
- Return false if no valid swap is found.