Isomorphic Strings - Problem

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Input & Output

Example 1 — Basic Isomorphic Case
$ Input: s = "egg", t = "add"
Output: true
💡 Note: Characters map consistently: 'e'→'a', 'g'→'d'. Pattern is preserved: first char different from next two, which are identical.
Example 2 — Non-Isomorphic Case
$ Input: s = "foo", t = "bar"
Output: false
💡 Note: Character 'o' appears twice in s but maps to different characters in t: 'o'→'a' and 'o'→'r'. This violates isomorphic property.
Example 3 — Identity Mapping
$ Input: s = "paper", t = "title"
Output: true
💡 Note: Valid mappings: 'p'→'t', 'a'→'i', 'p'→'t', 'e'→'l', 'r'→'e'. Each character maps consistently to exactly one other character.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • t.length == s.length
  • s and t consist of any valid ASCII character

Visualization

Tap to expand
Isomorphic Strings - Hash Map Bidirectional Mapping INPUT String s = "egg" e idx 0 g idx 1 g idx 2 String t = "add" a idx 0 d idx 1 d idx 2 Character Pattern: s: A B B t: A B B (Same pattern!) ALGORITHM STEPS 1 Create Two Maps s_to_t and t_to_s 2 Iterate Both Strings Compare char by char 3 Check Mappings Verify bidirectional 4 Add/Update Maps Store new mappings Mapping Tables: s_to_t e --> a g --> d t_to_s a --> e d --> g One-to-One Mapping OK No conflicts detected idx: 0,1,2 all passed FINAL RESULT Mapping Verification: e g a d s t Output: true Status: OK Strings are ISOMORPHIC Key Insight: Bidirectional mapping ensures no two characters map to the same character. If s[i] maps to t[i], then t[i] must also map back to s[i]. This prevents cases like "ab" --> "aa" where both 'a' and 'b' would map to 'a' (invalid for isomorphism). TutorialsPoint - Isomorphic Strings | Hash Map Bidirectional Mapping
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
102.5K Views
Medium Frequency
~15 min Avg. Time
2.8K 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