Isomorphic Strings solution explained

Two strings are isomorphic when you can rename the characters of the first, each one always to the same replacement and no two to the same one, to get the second. Check it in one pass by comparing where each character was last seen in its own string: at every position the two last-seen values must be equal. That is O(n) time, with memory bounded by the alphabet; a shorter Python check compares how many distinct characters and distinct pairs there are.

By Published 6 min read

The task, restated

You get two strings of the same length. Decide whether the second could be produced from the first by a substitution cipher: every occurrence of a given character is replaced by the same character, and two different characters are never replaced by the same one. A character may map to itself. Order is preserved, so you only rename, never move.

Examples made up for this walkthrough
FirstSecondIsomorphic?Why
kisspellYesk to p, i to e, s to l, used consistently
moonnoonNom and n would both have to become n
aabxyzNoa would have to become both x and y
abcxyzYesThree different characters on each side
two empty stringsYesNothing to rename
Examples made up for this walkthrough. Scroll sideways on a small screen.

Seeing it as shape, not letters

A useful way to think about this problem: replace each character with the position where it first appeared. kiss becomes 0 1 2 2, and pell becomes 0 1 2 2 too, so they share a shape. moon becomes 0 1 1 3 while noon becomes 0 1 1 0, which differ at the end. Two strings are isomorphic exactly when their shapes are identical. Every efficient solution is a way of comparing shapes without building them in full.

What interviewers listen for

Like its word-level sibling, this easy problem tests whether you enforce the mapping in both directions. It also gives you room to talk about the alphabet: dictionaries for arbitrary text, fixed arrays when the input is bytes or ASCII. Interviewers like candidates who state that assumption rather than silently indexing an array with any character.

Short answer in Python: count distinct pairs

If the mapping is one-to-one, the number of distinct characters in the first string, the number in the second, and the number of distinct (first, second) pairs are all equal. If a character maps to two different targets, there are more pairs than characters on the left. If two characters share a target, there are more characters on the left than on the right. The check is linear but builds three sets.

def isomorphic_sets(first, second):
    if len(first) != len(second):
        return False
    return len(set(first)) == len(set(second)) == len(set(zip(first, second)))
Python: three set sizes, O(n) time and space. Lengths must match first.

This is compact, and many interviewers accept it, but be ready to say why it is correct, because the reasoning is the point of the question.

One pass: first-seen positions

Keep a dictionary per string from character to the index where it first appeared. Walk both strings together. At each index, look up (or record) the first-seen index for each side. If they differ, the shapes differ, so return false.

def isomorphic(first, second):
    if len(first) != len(second):
        return False
    seen_a = {}
    seen_b = {}
    for i, (a, b) in enumerate(zip(first, second)):
        if seen_a.setdefault(a, i) != seen_b.setdefault(b, i):
            return False
    return True
Python: first-seen positions, O(n) time.

setdefault returns the stored index when the character is known and stores the current index when it is new, so one line handles both cases.

Arrays for a byte alphabet

When the strings are bytes, two arrays of 256 integers do the job of the dictionaries. Store, for each character, one more than the last index where it appeared, with 0 meaning never seen. At every position the stored values for the two current characters must match before you update both. Last-seen works as well as first-seen because the two strings are updated in lockstep, so their histories stay equal as long as the check keeps passing.

#include <array>
#include <string>

bool isomorphic(const std::string& first, const std::string& second) {
    if (first.size() != second.size()) return false;
    std::array<int, 256> lastA{};
    std::array<int, 256> lastB{};
    for (std::size_t i = 0; i < first.size(); ++i) {
        unsigned char a = static_cast<unsigned char>(first[i]);
        unsigned char b = static_cast<unsigned char>(second[i]);
        if (lastA[a] != lastB[b]) return false;
        lastA[a] = static_cast<int>(i) + 1;
        lastB[b] = static_cast<int>(i) + 1;
    }
    return true;
}
C++: two 256-slot arrays of last-seen positions, O(n) time, O(1) space.

The cast to unsigned char matters: a plain char may be signed, and a negative index would read outside the array. Mentioning it shows care with C++ details.

Cost of each approach

n is the string length, k the alphabet size
ApproachTimeExtra space
Compare every pair of positionsO(n²)O(1)
Distinct counts and pairs (sets)O(n)O(n) at worst
First-seen dictionariesO(n)O(k)
Last-seen arrays of 256O(n)O(1), fixed size
n is the string length, k the alphabet size. Scroll sideways on a small screen.

Edge cases to test

  • Different lengths: false.
  • Empty strings: true.
  • A string compared with itself: true.
  • Two characters collapsing into one, as in moon and noon.
  • One character splitting into two, as in aab and xyz.
  • Digits, punctuation or spaces mixed in, which a 26-slot array would not handle.

Common mistakes

  • Mapping only from the first string to the second.
  • Using 0 as both "never seen" and "seen at index 0" in the array version, which hides a mismatch at the first position.
  • Indexing an array with a signed char in C++.
  • Sizing an array for lowercase letters when the input can contain any character.
  • Checking that both strings have the same number of distinct characters and stopping there. ab and aa fail it, but abab and aabb pass it while not being isomorphic.

How to explain it out loud

Fictional example

Explaining with the shape idea
Candidate
I think of each string as a shape: replace every character with where it first appeared. Isomorphic strings have the same shape.
Candidate
I do not need to build the shapes. I walk both strings and compare the first-seen index of the current character on each side. Any difference means the mapping would break in one direction or the other.
Candidate
That is one pass. With dictionaries the space depends on the alphabet; if the input is bytes, I can use two fixed arrays of 256, so it is constant.

Word Pattern asks the same question with letters on one side and whole words on the other. Ransom Note is another character-table problem, but about counts rather than structure. Valid Anagram shows the fixed-array idea for counting. The coding problems hub lists all walkthroughs.

Using Natively in practice

This is a good problem for practicing a crisp explanation in under a minute. On Mac or Windows, Natively can read the prompt from a screenshot during a practice session and propose an approach, and it keeps a transcript of what you said so you can check whether you mentioned both directions and the alphabet assumption. The AI help for coding interviews page has more.

Questions people ask

How do you check if two strings are isomorphic?

Check the lengths, then walk both strings together, comparing the position where the current character was first (or last) seen in each string. Any difference means they are not isomorphic.

Why must the mapping be checked in both directions?

One character may not map to two targets, and two characters may not share one target. A single map from the first string only catches the first problem.

What is the time and space complexity?

O(n) time. Space is bounded by the alphabet, so with two fixed arrays of 256 for byte strings it is constant.

Is the Python set-size one-liner correct?

Yes, if the lengths match: the counts of distinct characters on each side and of distinct character pairs are all equal exactly when the mapping is one-to-one.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP