sagelearnai

Word Pattern

Difficulty: Easy · Pattern: Hashing · LeetCode #290

Given a pattern of letters and a string s of space-separated words, return whether s follows the pattern: a one-to-one correspondence between letters and words.

Examples

text
pattern = "abba", s = "dog cat cat dog"   →  true
pattern = "abba", s = "dog cat cat fish"  →  false
pattern = "aaaa", s = "dog cat cat dog"   →  false

Hints

  1. This is Isomorphic Strings with words instead of characters.
  2. Lengths must match first.

Approach

Split s into words; if the counts differ from the pattern length, return false. Then maintain two maps (letter → word, word → letter) and check consistency in both directions. O(n).

Complexity

Time: O(n). Space: O(n).

Python solution
def wordPattern(pattern, s):
    words = s.split()
    if len(words) != len(pattern):
        return False
    pw, wp = {}, {}
    for p, w in zip(pattern, words):
        if pw.setdefault(p, w) != w or wp.setdefault(w, p) != p:
            return False
    return True
JavaScript solution
function wordPattern(pattern, s) {
  const words = s.split(' ');
  if (words.length !== pattern.length) return false;
  const pw = new Map(), wp = new Map();
  for (let i = 0; i < words.length; i++) {
    const p = pattern[i], w = words[i];
    if ((pw.has(p) && pw.get(p) !== w) || (wp.has(w) && wp.get(w) !== p)) return false;
    pw.set(p, w); wp.set(w, p);
  }
  return true;
}