Taro Logo

Isomorphic Strings

#169 Most AskedEasy
Topics:
Strings

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"

Output: true

Explanation:

The strings s and t can be made identical by:

  • Mapping 'e' to 'a'.
  • Mapping 'g' to 'd'.

Example 2:

Input: s = "foo", t = "bar"

Output: false

Explanation:

The strings s and t can not be made identical as 'o' needs to be mapped to both 'a' and 'r'.

Example 3:

Input: s = "paper", t = "title"

Output: true

Constraints:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s and t consist of any valid ascii character.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set should we expect in the strings? Are we limited to standard ASCII, or do we need to support Unicode and extended character sets like emojis?
  2. Can the input strings be empty, and if so, should two empty strings be considered isomorphic?
  3. Is the mapping between characters strictly one-to-one (bijection), meaning two different characters in `s` cannot map to the same character in `t`?
  4. Are the input strings case-sensitive (e.g., does 'a' differ from 'A')?
  5. What should we return if the two strings are of different lengths?

Brute Force Solution

Approach

Imagine you are given two secret messages and want to check if you can completely translate one into the other by swapping every letter from the first message with a matching letter in the second message. The brute force strategy involves testing every single possible way to pair up the letters from both messages and checking if any of those combinations successfully turn the first message into the second one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first letter of the first message and try pairing it with every single letter available in the second message one by one.
  2. For each of those potential pairings, pretend that every time the first letter appears anywhere else, it must always transform into the chosen partner from the second message.
  3. Next, move to the second letter of the first message, and again, try pairing it with every remaining possibility in the second message, making sure you never assign two different letters to the exact same partner.
  4. Continue this process for every unique letter in the entire first message, exhaustively testing all combinations and permutations of letter assignments.
  5. At the end of each complete combination test, check if applying all those rules successfully transforms the first entire message into the second entire message without breaking any consistency rules.
  6. If you successfully test a combination where every letter matches up perfectly and consistently, you have found your answer and can confirm the messages match.

Code Implementation

def isIsomorphic(source_string, target_string):
    import itertools

    if len(source_string) != len(target_string):
        return False

    unique_source_chars = list(set(source_string))
    unique_target_chars = list(set(target_string))

    if len(unique_source_chars) != len(unique_target_chars):
        return False

    # Generate all possible letter mappings to exhaustively test every combination strategy
    for target_permutation in itertools.permutations(unique_target_chars, len(unique_source_chars)):
        mapping_dictionary = dict(zip(unique_source_chars, target_permutation))

        transformed_chars = []

        for character in source_string:
            transformed_chars.append(mapping_dictionary[character])

        # Verify if the current mapping successfully transforms the entire source into the target
        if "".join(transformed_chars) == target_string:
            return True

    # If all brute force mapping combinations fail, the strings cannot be isomorphic
    return False

Big(O) Analysis

Time Complexity
O(26^n) – For each of the n unique letters in the first message, we must try pairing it with up to 26 possible alphabet letters in the second message while avoiding duplicate assignments. This recursive permutation and backtracking process creates a decision tree of choices up to n levels deep. The total operations therefore approximate an exponential formula bounded by the number of alphabet choices raised to the number of unique characters, which simplifies to O(26^n).
Space Complexity
O(1) – The brute force strategy described tests every possible combination and permutation of letter assignments without maintaining any persistent auxiliary data structures like hash maps or recursion stacks across the entire algorithm. The algorithm only requires a few primitive variables to track the current pairing loops and transformation rules being tested on the fly. Since the character set is bounded by a fixed alphabet size such as ASCII or the 26 lowercase English letters rather than growing with the input size N, the extra memory remains constant. Therefore, the auxiliary space complexity simplifies to O(1) constant space.

Optimal Solution

Approach

To check if two things match in a special structural way, we can pair up their individual pieces one by one as we move along. By keeping track of who is paired with who, we can immediately catch if someone tries to pair with two different partners or if a partner gets stolen.

Here's how the algorithm would work step-by-step:

  1. Look at the two things side by side, starting from the very beginning.
  2. Take the current piece from the first thing and the current piece from the second thing, and introduce them to each other as partners.
  3. Check our memory book to make sure neither of these pieces has already been introduced to someone else with a different partner.
  4. If either piece is already matched up with a different partner than the one we are seeing right now, we know the structure fails and we can stop immediately.
  5. If the pairing is fresh and valid, write it down in our memory book so we remember it for the rest of the journey.
  6. Smoothly glide to the next pair of pieces and repeat the same check.
  7. If we successfully reach the very end without any partner mix-ups, give a thumbs up because they are a matching pair.

Code Implementation

def is_isomorphic(first_string, second_string):
    first_to_second_map = {}
    second_to_first_map = {}

    for char_index in range(len(first_string)):
        char_from_first = first_string[char_index]
        char_from_second = second_string[char_index]

        # We must ensure a consistent one-to-one mapping in both directions.
        if char_from_first in first_to_second_map and first_to_second_map[char_from_first] != char_from_second:
            return False

        # Prevent two distinct characters from mapping to the same target character.
        if char_from_second in second_to_first_map and second_to_first_map[char_from_second] != char_from_first:
            return False

        first_to_second_map[char_from_first] = char_from_second
        second_to_first_map[char_from_second] = char_from_first

    return True

Big(O) Analysis

Time Complexity
O(n) – To determine if the strings are isomorphic, we iterate through each of the n characters in the strings side by side once. In each step, we perform constant-time hash map lookups and insertions to check and record character partnerships. This means the number of operations scales linearly with the input string length n, leading to approximately n steps. Simplifying this gives a final time complexity of O(n).
Space Complexity
O(1) – The memory book mentioned in the steps is implemented using hash maps or fixed-size arrays to store character pairings. Because the character set is restricted to a fixed alphabet such as ASCII or Unicode, the number of unique entries in the memory book cannot exceed this constant limit regardless of the input string length N. Therefore, the auxiliary space remains constant, resulting in O(1) space complexity.

Edge Cases

Empty strings or strings of length one
How to Handle:
Return true immediately because empty strings are trivially isomorphic and single characters always map correctly.
Strings of unequal length
How to Handle:
Return false right away since strings must have the same length to establish a one-to-one character mapping.
Many-to-one mapping attempt where two different characters in s map to the same character in t
How to Handle:
Maintain a reverse mapping or set of used target characters to detect collisions and return false.
Strings with all identical characters
How to Handle:
Verify that a single character maps consistently to another single character without triggering mapping conflicts.
Strings with completely disjoint character sets
How to Handle:
Process each unique character pair sequentially to ensure correct bi-directional mapping is established.
Maximum length strings with large character sets like Unicode
How to Handle:
Use hash maps or fixed-size frequency arrays to achieve optimal linear time complexity and scale efficiently.
Strings that initially map correctly but diverge at the final character
How to Handle:
Iterate through the entire length of the strings to ensure consistency until the last position.
0/245 completed