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 Transforms Into Another String Hash Map Validation Approach INPUT str1 = "aab" a a b 0 1 2 str2 = "xxy" x x y 0 1 2 Character Mapping a x b y ALGORITHM STEPS 1 Build Mapping Map each char in str1 to corresponding str2 2 Check Consistency Same char must map to same target always 3 Check Cycles If all 26 chars used, need temp char space 4 Validate Result Return true if all checks pass HashMap State {'a': 'x', 'b': 'y'} unique targets: 2 FINAL RESULT Transformation Valid BEFORE "aab" AFTER "xxy" Conversions Applied: Step 1: a --> x Step 2: b --> y (2 conversions total) Output: true Transformation is possible! [OK] All validations passed Key Insight: A valid transformation requires: (1) Each character in str1 maps consistently to one character in str2, and (2) If str2 uses all 26 letters and str1 != str2, transformation is impossible (no temp char available). Time: O(n), Space: O(26) = O(1) using HashMap to track character mappings. TutorialsPoint - String Transforms Into Another String | Hash Map Validation Approach
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