String Transforms Into Another String Problem
Description
LeetCode Problem 1153.
Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions.
In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character.
Return true if and only if you can transform str1 into str2.
Example 1:
Input: str1 = "aabcc", str2 = "ccdee"
Output: true
Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
Example 2:
Input: str1 = "leetcode", str2 = "codeleet"
Output: false
Explanation: There is no way to transform str1 to str2.
Constraints:
1 <= str1.length == str2.length <= 10^4str1andstr2contain only lowercase English letters.
Solution
Approach: Consistent Mapping + a Spare Letter
A conversion changes all occurrences of a letter at once, so two positions that hold the same letter in str1 always hold the same letter afterwards. That gives the first condition: every letter of str1 must correspond to a single letter of str2. If some letter a lines up with b in one place and with c in another, the answer is false (Example 2: in "leetcode" and "codeleet", e would have to become both o and d). Two different letters may map to the same letter, though: we can first turn a into c, and later turn all those cs, together with the original ones, into something else.
Is a consistent mapping always enough? Cycles are the problem. For "ab" -> "ba", converting a to b directly would merge the two letters forever. The fix is a temporary letter: a -> x, b -> a, x -> b. In general, any chain or cycle can be done in the right order as long as there is one letter we are free to use as a temporary. Such a letter exists exactly when str2 does not use all 26 letters.
If str2 uses all 26 letters and the strings differ, the mapping would have to be a one-to-one map onto all 26 letters that moves at least one letter. Then the very first conversion would merge two letters of str1 into one, and after that there are at most 25 distinct letters, too few to make all 26 of str2. So the answer is false.
The one exception is str1 == str2: zero conversions are needed, even when all 26 letters appear. So check that first.
Complexity: O(n) time and O(1) extra space (the mapping has at most 26 entries).
class Solution:
def canConvert(self, str1: str, str2: str) -> bool:
if str1 == str2:
return True
# Every occurrence of a letter changes together, so each letter of str1 must map to one letter of str2.
mapping = {}
for a, b in zip(str1, str2):
if mapping.setdefault(a, b) != b:
return False
# A spare letter (unused in str2) is needed as a temporary to break cycles like a -> b, b -> a.
return len(set(str2)) < 26