Isomorphic Strings

Problem Summary

(Write in your own words, not copied from LeetCode. This forces comprehension.)

Key Observations

(Patterns, constraints, or hints in the problem statement.)

Main Concepts Used

(Mark the CS concepts or algorithms used.)

Time & Space Complexity

Code

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        mapOfStoT = {} # O(n)
        mappedSoFar = set() # O(1)

        for i in range(len(s)): # O(n + m)
            charInS = s[i]
            charInT = t[i]

            if charInS in mapOfStoT:
                # check whether mapping matches charInT
                storedMapping = mapOfStoT[charInS]
                if storedMapping != charInT:
                    return False
            else:
                if charInT in mappedSoFar:
                    return False
                mapOfStoT[charInS] = charInT
                mappedSoFar.add(charInT)
        return True

Common Mistakes / Things I Got Stuck On

Optimized Code

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        mapStoT, mapTtoS = {}, {}

        for c1, c2 in zip(s, t):
            if c1 in mapStoT:
                if c2 != mapStoT[c1]:
                    return False
            else:
                mapStoT[c1] = c2

            if c2 in mapTtoS:
                if c1 != mapTtoS[c2]:
                    return False
            else:
                mapTtoS[c2] = c1
        return True