Notes

Personal notes on various topics

View on GitHub

Intuition

To check if a string follows a given pattern, we need to ensure a bijection between pattern letters and words in the string. Each letter should map to a unique word, and each word should map to a unique letter.

Approach

Complexity

Code

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        if len(pattern) != len(words):
            return False

        mapped_dict = {}
        mapped_set = set()

        for p, word in zip(pattern, words):
            mapped_dict[p] = mapped_dict.get(p, word)
            if mapped_dict[p] != word:
                return False

            mapped_set.add(word)

        if len(mapped_set) != len(mapped_dict):
            return False
        return True

Back to Problem Statement