class Solution:
    def wordPattern(self, pattern: str, str: str) -> bool:
        """
        time  O(N)  space O(2M)  M: unique # words 
         step1:  split str, check length of str and pattern
         step2: create two hash map, loop each element in str/ pattern
         step3: check if pattern[i] in d1
                   /                   \
                  yes             if str[i] in d2
                  |                     /    \
?  d1[ pattern[i]]== str[i]            yes   no 
           /     \                      |     |
        yes      no                 False     d1[str[i]] = pattern[i]   d2[pattern[i]] = str[i]
        |        |
    continue    Fale
       """
        str = str.split(' ')
        if len(str) != len(pattern):
            return False
        d_str = {}
        d_pat = {}
        for i in range(len(str)):
            if pattern[i] not in d_pat:
                if str[i] not in d_str:
                    d_str[str[i]] = pattern[i]
                    d_pat[pattern[i]] = str[i]
                else:
                    return False
            else:
                if d_pat[pattern[i]] != str[i]:
                    return False
        return True

optimize

class Solution:
    def wordPattern(self, pattern: str, str: str) -> bool:
        # time  O(N)  space O(M)  M: unique # words 
        # step1:  split str, check length of str and pattern
        # step2: create one hash map, loop each element in str/ pattern
        # step3: create unique key for element in both str and pattern with '{}_xxx'.format(element)
        # step4: check if element in str and pattern  as key in the hash map, if not, d[ele] = idx 
        # step5: in the same loop, check if these two keys has the same value in the hash map,  if not=> return False,  after whole loop ends, means str follows pattern 
        str = str.split(' ')

        if len(str) != len(pattern):
            return False
        d = {}
        for i in range(len(str)):
            str_c = '{}_strc'.format(str[i])
            pat_c = '{}_patc'.format(pattern[i])
    
            if str_c not in d:
                d[str_c] = i   
            if pat_c not in d:
                d[pat_c] = i
            if d[str_c] != d[pat_c]:
                return False
        return True