# 290 Word Pattern

Given a`pattern`and a string`str`, find if`str`follows the same pattern.

Here **follow** means a full match, such that there is a bijection between a letter in`pattern`and a **non-empty** word in`str`.

**Examples:**

1. pattern = `"abba"`, str = `"dog cat cat dog"` should return `true`. &#x20;
2. pattern = `"abba"`, str = `"dog cat cat fish"` should return `false`. &#x20;
3. pattern = `"aaaa"`, str = `"dog cat cat dog"` should return `false`. &#x20;
4. pattern = `"abba"`, str = `"dog dog dog dog"` should return `false`.

**Notes:**\
You may assume`pattern`contains only lowercase letters, and`str`contains lowercase letters separated by a single space.

**The Idea:** Use a bidirectional map to check for a one to one mapping between each character in the pattern and each word in the sentence.

**Complexity:** O(n) time and O(2n) space:

```python
def wordPattern(self, pattern, str):
    """
    :type pattern: str
    :type str: str
    :rtype: bool
    """
    if len(pattern) != len(str.split()):
        return False
    chars_word = {}
    word_char = {}
    for char, word in zip(pattern, str.split()):
        if (chars_word.__contains__(char) and chars_word[char] != word)\
                or word_char.__contains__(word) and word_char[word] != char:
            return False
        elif not chars_word.__contains__(char):
            chars_word[char] = word
            word_char[word] = char

    return True
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/290-word-pattern.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
