Skip to content
Problem 205 · LeetCode 205(opens in a new tab)

Isomorphic Strings

EasyHash tables

You are given two strings, s and t, of the same length. Decide whether you can turn s into t by renaming its characters: every copy of a character is swapped for the same new character, and the order stays as it is.

Two different characters of s may not be renamed to the same character. A character may keep its own name. Return true if such a renaming exists.

Example 1

Input:  s = "bass", t = "kiss"
Output: true
Why:    rename b → k, a → i, s → s
2 more examples and the constraints

Example 2

Input:  s = "moon", t = "tree"
Output: false
Why:    o would have to become both r and e

Example 3

Input:  s = "loop", t = "deed"
Output: false
Why:    l and p would both have to become d

Constraints

  • 1 ≤ length of s ≤ 50,000
  • t is exactly as long as s
  • Both strings may hold any ASCII character

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare every pairO(n²)
  2. Two maps, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 charactersVerdict
Compare every pairO(n²)
Correct, far too slow
Two maps, one passO(n)
Best; one pass, done

n = length of s, k = number of distinct characters.

Edge cases to test

  • Two letters onto one. "ab" and "cc" is false; only the t → s map notices.
  • One letter onto two. "cc" and "ab" is false; the s → t map notices.
  • Not only letters. Digits, spaces and symbols are characters too: "4 4" and "x-x" is true.
  • Same string. Every character keeps its own name, which is allowed.
  • Clash at the very end. Keep checking to the last character; do not stop early on a true answer.

Common mistakes

  • Using only the s → t map, so "ab" and "cc" wrongly comes back true.
  • Comparing the sets of characters or their counts, which ignores where they repeat.
  • Assuming only lower-case letters and sizing an array to 26.

How to talk through it

  1. 1Clarify. Same length always? Which characters can appear? May a character map to itself?
  2. 2Restate the rule. Each character of s has exactly one partner in t, and no two share a partner: a one-to-one mapping.
  3. 3Give the brute force. Compare the repeat pattern over every pair of positions; O(n²).
  4. 4Code two maps. Check both directions before storing. Say which mistake each map catches.
  5. 5Test out loud. Run "ab"/"cc" and "cc"/"ab": each one fails only one of the two maps.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?