Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Check whether two strings are isomorphic (characters map one-to-one consistently).

Problem: Check whether two strings are isomorphic (characters map one-to-one consistently).
def iso(s, t):
    return len(set(s)) == len(set(t)) == len(set(zip(s, t)))
print(iso("egg", "add"), iso("foo", "bar"), iso("badc", "baba"), iso("paper", "title"))
What is printed?
  1. A. True False True True
  2. B. True False False True
  3. C. True True False True
  4. D. False False False True

Correct answer: B. True False False True

A valid bijection means the number of distinct (s, t) pairs equals the distinct letters on each side. "badc" has 4 distinct letters but "baba" only 2, so two letters of s would have to share an image (a→a and c→a). "foo" fails the other way: 'o' must map to both 'a' and 'r'. One-directional checks pass such cases by mistake. O(n).

More Coding Interview Problems questions

Exams that ask this topic