Skip to main content
Back to problems
#205
Easy Algorithms

Isomorphic strings

Hash Table String
48.1% acceptance
Jan 12, 2026
10467
2277
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn is_isomorphic(s: String, t: String) -> bool {
    let mut s_to_t = std::collections::HashMap::new();
    let mut t_to_s = std::collections::HashMap::new();
    
    for (sc, tc) in s.chars().zip(t.chars()) {
      match (s_to_t.get(&sc), t_to_s.get(&tc)) {
        (Some(&mapped_t), Some(&mapped_s)) => {
          if mapped_t != tc || mapped_s != sc {
            return false;
          }
        }
        (None, None) => {
          s_to_t.insert(sc, tc);
          t_to_s.insert(tc, sc);
        }
        _ => return false,
      }
    }
    true
  }
}