DSA AnimatorREVISION VIDEOS
← Back to problems
New

Isomorphic Strings — LeetCode 205 video explanation

Two strings are isomorphic if the characters of the first can be replaced to get the second. Each character must always map to the same character, and no two characters can map to the same one.

Loading videos…

DSA Animator › DSA Revision › Strings › Isomorphic Strings

Key moments in the Isomorphic Strings video

0:04Problem0:15Example0:23Brute force0:33Key idea0:43Dry run1:03Code1:16Takeaway

What you will learn

Remember: isomorphic means a one-to-one mapping, so check both directions. Two maps, one for each direction. The video solves Isomorphic Strings (LeetCode 205, Easy) with the Two Hash Maps pattern from the Strings topic, and you can replay every step in the interactive Isomorphic Strings animation.

Isomorphic Strings video transcript

Problem

Two strings are isomorphic if the characters of the first can be replaced to get the second. Each character must always map to the same character, and no two characters can map to the same one.

Example

egg and add are isomorphic: e maps to a, and g maps to d. foo and bar are not, because o would need to map to both a and r.

Brute force

Checking only one direction is the common mistake. For badc and baba, b maps to b and a to a, but then d would also map to b, which must not happen.

Key idea

Keep two maps: one from the first string to the second, and one from the second back to the first. At each position, the pair must agree with both maps, or be new to both.

Dry run

e and a are new, so record e to a, and a to e. g and d are new, so record g to d, and d to g. g and d again, and both maps agree. So egg and add are isomorphic. For foo and bar, o maps to a at index 1, but at index 2 o meets r. That conflicts with the map, so foo and bar are not isomorphic.

Code

In code, loop over both strings together. If either map already has a different partner for the character, return false. Otherwise record the pair in both maps. It's O of n time, and O of 1 space for a fixed alphabet.

Takeaway

Remember: isomorphic means a one-to-one mapping, so check both directions. Two maps, one for each direction.

More Strings revision videos

← All 185 DSA revision videos