String Transforms Into Another String - Problem

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.

Input & Output

Example 1 — Simple Mapping
$ Input: str1 = "aab", str2 = "xxy"
Output: true
💡 Note: We can convert 'a' to 'x' and 'b' to 'y': aab → xab → xxy. Each character in str1 maps consistently to one character in str2.
Example 2 — Conflicting Mapping
$ Input: str1 = "leetcode", str2 = "codeleet"
Output: false
💡 Note: Character 'e' would need to map to both 'e' and 't', which is impossible. We cannot have one character map to multiple different characters.
Example 3 — All Characters Used
$ Input: str1 = "abcdefghijklmnopqrstuvwxyz", str2 = "bcdefghijklmnopqrstuvwxyza"
Output: false
💡 Note: This creates a cycle where 'a'→'b'→'c'→...→'z'→'a', but all 26 characters are used in str2, so we have no temporary character to break the cycle.

Constraints

  • 1 ≤ str1.length ≤ 104
  • str2.length == str1.length
  • str1 and str2 consist of lowercase English letters only

Visualization

Tap to expand
String Transformation: Character MappingSource: "aab"Target: "xxy"abxya → xb → yTransformation Possible: true
Understanding the Visualization
1
Input Strings
Two strings of equal length with character mapping requirements
2
Character Mapping
Build one-to-one mapping from source to target characters
3
Validation
Check consistency and cycle resolution possibility
Key Takeaway
🎯 Key Insight: Each character can only map to one target, and cycles need temporary characters for resolution
Asked in
Google 35 Facebook 28
24.5K Views
Medium Frequency
~35 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