iq.lab
Python starts when a code cell comes near or you run one
easyHash maps and sets target 15 min

Isomorphic strings

Two strings s and t have the same length. They are isomorphic (they have the same shape) when replacing the characters of s can turn it into t under two rules:

  1. Every copy of a character gets the same replacement. If one a becomes x, every a becomes x.
  2. Different characters get different replacements. If a becomes x, no other character can also become x.

All replacements happen at once, and a character may become itself: "abc" and "abd" are isomorphic, since a and b stay and c becomes d. Return True if s and t are isomorphic, and False otherwise.

Example 1
Inputs = "ball", t = "tree"OutputTrue

b becomes t, a becomes r, and l becomes e. Both copies of l become e.

Example 2
Inputs = "moon", t = "noon"OutputFalse

m would become n, and n would also stay n. Two different characters cannot become the same one.

Example 3
Inputs = "aab", t = "xyz"OutputFalse

The first a becomes x, so the second a must become x too, but it lines up with y.

Constraints
  • 1 ≤ len(s) ≤ 5 × 104

  • len(t) == len(s)

  • Characters can be any ASCII characters, including digits, spaces and punctuation.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.