String Transforms Into Another String - Problem
You're given two strings str1 and str2 of equal length. Your task is to determine whether you can transform str1 into str2 through a series of character conversions.
In each conversion operation, you can:
- Choose any character that appears in
str1 - Replace all occurrences of that character with any other lowercase English letter
The challenge is that this transformation must be consistent - if you map character 'a' to 'b', then every 'a' in the string must become 'b'. Think of it as a character substitution cipher where each character has exactly one mapping.
Examples:
"abc" → "bca"is possible: a→b, b→c, c→a"ab" → "aa"is impossible: both 'a' and 'b' would need to map to 'a'"abcdefghijklmnopqrstuvwxyz" → "bcdefghijklmnopqrstuvwxyza"is impossible: no free character to use as intermediate
Input & Output
example_1.py — Python
$
Input:
str1 = "aabcc", str2 = "ccdee"
›
Output:
true
💡 Note:
We can transform by mapping: a→c, b→d, c→e. This creates the mapping {a:c, b:d, c:e} which is one-to-one and we have unused characters (a,b,f-z) available.
example_2.py — Python
$
Input:
str1 = "leetcode", str2 = "codeleet"
›
Output:
false
💡 Note:
We need mapping: l→c, e→o, e→d, t→e, c→l, o→e, d→e, e→t. But 'e' cannot map to both 'o' and 'd' simultaneously. The mapping is inconsistent.
example_3.py — Python
$
Input:
str1 = "abcdefghijklmnopqrstuvwxyz", str2 = "bcdefghijklmnopqrstuvwxyza"
›
Output:
false
💡 Note:
This creates a cycle where every character maps to the next one (a→b→c→...→z→a), but there's no unused character to help break the cycle since all 26 letters are used.
Constraints
- 1 ≤ str1.length ≤ 104
- str2.length == str1.length
- str1 and str2 consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Build Character Mapping
Create a mapping from each character in str1 to its corresponding character in str2
2
Validate Consistency
Ensure each character maps to exactly one target (no contradictions)
3
Check One-to-One Property
Verify no two different characters map to the same target
4
Verify Cycle Breaking
Ensure unused characters exist to handle transformation cycles
Key Takeaway
🎯 Key Insight: The transformation is possible if and only if: (1) the character mapping is consistent and one-to-one, AND (2) there's at least one unused character in the alphabet to serve as a temporary placeholder for breaking cycles.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code