AAlgoLoopSpaced repetition for LeetCode
EASYHash Map / SetLeetCode ↗

Isomorphic Strings

The key idea

Isomorphism is a one-to-one (bijective) character mapping. As you scan the two strings in lockstep, the pair (s[i], t[i]) must obey two rules at once: s[i] must always map to the same t[i] it mapped to before (no character maps to two targets), and that t[i] must not already be claimed by a different source character (no two characters collapse into one target). Tracking both directions catches every violation in a single linear pass.

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.

Constraints

Examples

Input: s = "egg", t = "add" Output: true
Input: s = "foo", t = "bar" Output: false
Input: s = "paper", t = "title" Output: true

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems