Show problems as
Classic problem #205EasyHash TableString

Isomorphic Strings

Real-world version: Interchangeable Route Codes
Tracked in this browser only
Read Isomorphic Strings on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Two depots label the same delivery run with their own character codes, first and second, of equal length. Dispatch wants to know whether the two labels describe the same run under a consistent relabelling of characters.

Call the codes interchangeable when there is a substitution table that turns first into second position by position, subject to two rules:

  • every occurrence of a given character in first must be substituted by the same character in second
  • no two different characters of first may be substituted by the same character of second

A character is allowed to substitute to itself. Codes may contain any ASCII characters, including digits, spaces and punctuation, and uppercase is a different character from lowercase. Return true when the codes are interchangeable and false otherwise.

Examples

Example 1

Input
first = "mim", second = "tot"
Output
true

Substituting m for t and i for o rewrites the first label as the second, and the repeated character stays consistent at both ends.

Example 2

Input
first = "kk", second = "qr"
Output
false

The single character of the first label would have to become two different characters, which no substitution table allows.

Example 3

Input
first = "dip dip", second = "kop kop"
Output
true

The blank counts as an ordinary character and maps to itself, while d, i and p take three distinct partners.

Constraints

  • 1 <= first.length <= 5 * 10^4
  • second.length == first.length
  • first and second consist of any valid ascii characters

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def codes_interchangeable(first: str, second: str) -> bool:
Java
public boolean codesInterchangeable(String first, String second)