SDE & MLE Prep

290. Word Pattern

Problem

Decide whether the words of s follow pattern: there must be a one-to-one mapping between pattern letters and words, so equal letters correspond to equal words and different letters to different words.

Example: pattern = "abba", s = "dog cat cat dog" → true; s = "dog cat cat fish" → false

Same idea as Isomorphic Strings: the mapping letter ↔ word must be a bijection, so keep both directions and reject any conflict. Also reject different lengths.

Complexity: O(n).

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        if len(words) != len(pattern):
            return False
        p2w, w2p = {}, {}
        for p, w in zip(pattern, words):
            if p2w.setdefault(p, w) != w or w2p.setdefault(w, p) != p:
                return False
        return True