Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Isomorphic Strings



Problem Statement

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

Two strings are isomorphic if the characters in s can be replaced to get t. The replacement must be consistent — every character in s must map to exactly one character in t, and no two characters from s can map to the same character in t.

The character mapping should be one-to-one and should preserve the order of characters. Return true if the strings are isomorphic, otherwise return false.

Examples

stOutputDescription
eggaddtrue'e' → 'a', 'g' → 'd' — consistent mapping
foobarfalse'o' maps to two different characters, which breaks the rule
papertitletrue'p' → 't', 'a' → 'i', 'e' → 'l', 'r' → 'e'
abaafalse'a' → 'a' and 'b' → 'a' — two characters from 's' map to same char in 't'
abcdeftrueEach character maps uniquely and consistently
trueBoth strings are empty — trivially isomorphic
abcfalseOne string is empty, the other is not
abcfalseOne string is empty, the other is not
abcazbxztrue'a' → 'z', 'b' → 'b', 'c' → 'x' — all mappings valid
abcazbxyfalse'a' maps to both 'z' and 'y' — mapping is inconsistent

Solution

To check whether two strings are isomorphic, we need to understand whether we can map each character in the first string to a unique character in the second string — and do so consistently throughout the entire string.

Imagine we are translating every character from s to t. If 'a' in s maps to 'x' in t, then every time we see 'a' in s, it must be translated to 'x'. If we see 'a' later mapping to a different character (like 'y'), the strings are not isomorphic.

We also need to make sure that no two different characters in s map to the same character in t. For example, if both 'a' and 'b' map to 'x', that breaks the one-to-one requirement.

To implement this, we can use two hash maps (or dictionaries):

  • s_to_t: Maps characters from s to t.
  • t_to_s: Maps characters from t to s.

As we iterate through the characters of both strings, we:

  • Check if the current character from s has already been mapped to something in t. If it has, and the mapping doesn't match the current character in t, we return false.
  • Similarly, we check that the character in t hasn't already been assigned to a different character from s.

If we finish the loop and all mappings are valid, we return true.

Special Cases to Consider:

  • Empty strings: Two empty strings are trivially isomorphic — no characters means no conflicts.
  • Different lengths: If the strings are of unequal length, they can never be isomorphic, because we can't map characters one-to-one.
  • Repeated characters: It's okay if a character appears multiple times — as long as it always maps to the same character in the other string, and no conflicts arise.

This explanation focuses on helping beginners reason through character mapping with clarity before worrying about code or efficiency.

Visualization

Algorithm Steps

  1. Initialize two HashMaps: s_to_t and t_to_s.
  2. Loop through each character in both strings.
  3. For each character pair (sc, tc) from s and t:
    • If sc is mapped in s_to_t, it must map to tc.
    • If tc is mapped in t_to_s, it must map to sc.
  4. If any mismatch is found, return false.
  5. After the loop, return true.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def is_isomorphic(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    s_to_t = {}
    t_to_s = {}

    for sc, tc in zip(s, t):
        if sc in s_to_t:
            if s_to_t[sc] != tc:
                return False
        else:
            s_to_t[sc] = tc

        if tc in t_to_s:
            if t_to_s[tc] != sc:
                return False
        else:
            t_to_s[tc] = sc

    return True

# Example Usage
print(is_isomorphic("egg", "add"))  # True
print(is_isomorphic("foo", "bar"))  # False

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)We traverse both strings once, checking and updating maps in constant time.
Average CaseO(n)Each character mapping takes constant time; total work is proportional to string length.
Average CaseO(n)In the worst case, every character in both strings is unique and requires a mapping.

Space Complexity

O(n)

Explanation: Two hash maps are used that at most store all unique characters of the strings.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M