The Letter Mapper

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L4
Asked in
BetterUp

Problem

Given two equal-length strings s and t, return True if they are isomorphic: there exists a bijection between characters of s and t such that each s[i] maps to t[i] consistently (no two different characters map to the same character).

A consistent substitution, or not.

Example 1

Input:

s = "egg", t = "add"

Output:

true

Example 2

Input:

s = "foo", t = "bar"

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This tests bijective mapping verification, a pattern used in encoding validation and schema mapping. It probes whether a candidate can enforce both forward and reverse mapping uniqueness simultaneously.


Break down the requirements

Step 1: Build forward and reverse mappings

Map each character in string A to the corresponding character in string B, and vice versa.

Step 2: Check consistency on every pair

If a character in A was previously mapped to a different character in B (or vice versa), the strings are not isomorphic.


The solution

Dual-mapping consistency check
def is_isomorphic(s: str, t: str) -> bool:
    map_s_to_t = {}
    map_t_to_s = {}
    for i in range(len(s)):
        ch_s = s[i]
        ch_t = t[i]
        if ch_s in map_s_to_t:
            if map_s_to_t[ch_s] != ch_t:
                return False
        else:
            map_s_to_t[ch_s] = ch_t
        if ch_t in map_t_to_s:
            if map_t_to_s[ch_t] != ch_s:
                return False
        else:
            map_t_to_s[ch_t] = ch_s
    return True

Common follow-up questions