InterviewPrepKit

Home / Coding / Arrays & Hashing

Word Pattern

easy Original ↗
Solving tips
  • Recognize this as a bijection / consistent-relabeling problem (sibling of Isomorphic Strings): the mapping must be enforced in BOTH directions, not just letter to word.
  • Split s into words and immediately return False if the word count differs from the pattern length, or zip will silently hide a mismatch.
  • Keep two hash maps (letter to word and word to letter) checked in lockstep, or compare first-occurrence-index fingerprints; either runs in O(n+m) time and space.
  • The classic trap is using only a forward letter to word map: 'abba' vs 'dog dog dog dog' passes it because two letters mapping to one word goes undetected.

Problem

You’re given a pattern string of lowercase letters and a sentence s of lowercase words separated by single spaces. Decide whether s follows the pattern: there must be a one-to-one correspondence (a bijection) between the letters of pattern and the words of s, such that replacing each letter by its word reproduces the sentence exactly.

“One-to-one” cuts both ways: a letter always maps to the same word, and no two different letters map to the same word.

Examples

  • pattern = "abba", s = "dog cat cat dog"True — a↔dog, b↔cat is a consistent bijection.
  • pattern = "abba", s = "dog cat cat fish"Falsea would have to be both “dog” and “fish”.
  • pattern = "abba", s = "dog dog dog dog"False — both a and b would map to “dog”, which breaks one-to-one.

Constraints

  • 1 <= pattern.length <= 300, letters only.
  • 1 <= s.length <= 3000; words are lowercase letters separated by single spaces (no leading/trailing spaces).

Tiny bounds — correctness of the mapping logic, not speed, is the whole game.

Think about it first

Hint 1 Split `s` into words first. If the number of words differs from the number of letters, you can answer immediately.
Hint 2 A dict from letter → word catches "a maps to two different words". What input breaks a solution that has *only* that dict? (Look at example 3.)
Hint 3 Keep two maps — letter → word and word → letter — and walk the pairs in lockstep; any disagreement with an existing entry in either map means `False`. (Equivalently: letter and word must always have matching first-occurrence positions.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.