Isomorphic Strings
Real-world version: Interchangeable Route CodesThe 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
firstmust be substituted by the same character insecond - no two different characters of
firstmay be substituted by the same character ofsecond
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.
def codes_interchangeable(first: str, second: str) -> bool:public boolean codesInterchangeable(String first, String second)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's