Intermediate Level

Implement the isomorphicStringsCheck method that checks whether two strings follow the same character mapping pattern.

The input contains two strings, first and second. Your task is to check whether both strings are isomorphic.

Two strings are isomorphic when every character in the first string can be consistently replaced to form the second string, and no two different characters map to the same character.

For example, egg and add are isomorphic because e maps to a and g maps to d.

Example 1

Input
first (string) = egg
second (string) = add
Returns (boolean) true

Example 2

Input
first (string) = foo
second (string) = bar
Returns (boolean) false

Example 3

Input
first (string) = paper
second (string) = title
Returns (boolean) true

Check the character mapping in both directions.

A map from first to second ensures that the same character always maps to the same target character. A second map from second to first prevents two different source characters from using the same target character.

If any mapping conflict is found, the strings are not isomorphic.

Pseudocode:

function isomorphicStringsCheck(first, second):
    if lengths are different:
        return false
    create empty map forward
    create empty map backward
    for i from 0 to length - 1:
        a = first[i]
        b = second[i]
        if a exists in forward and forward[a] != b:
            return false
        if b exists in backward and backward[b] != a:
            return false
        forward[a] = b
        backward[b] = a
    return true
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.