Word Pattern
Word Pattern is LeetCode 290 (Easy). You get a pattern of lowercase letters and a string s of words separated by single spaces. Return true if s follows the pattern, which means both of these hold:
- a letter always stands for the same word;
- two different letters never stand for the same word.
The pattern has at most 300 letters and s at most 3,000 characters, so one pass over the pairs is all it takes.
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
- s contains only lowercase English letters and spaces ' '.
- s does not contain any leading or trailing spaces.
- All the words in s are separated by a single space.
Intuition
Put the words under the letters, one word per letter. The string follows the pattern exactly when this pairing is a one-to-one mapping, and that rule has two halves:
- Letter side: a letter seen before must meet the same word again.
- Word side: a word seen before must meet the same letter again.
One dictionary from letters to words only guards the first half; two letters could quietly share a word and it would never notice. So keep two hash maps, one for each direction, and stop at the first pair that disagrees with either of them. If every pair agrees with both, the pairing is one-to-one.
"Does this sequence follow that pattern?" with a one-to-one rule is a bijection check. The same two-map test solves Isomorphic Strings, where both sides are single characters.
Approach
Before reading on, decide what must be true about a letter you have seen before, and what must be true about a word you have seen before. Then decide what to check before you pair anything at all. Aim for one pass.
Split and compare the counts
Split s on spaces into words. If the number of words differs from the number of letters, return false at once: some letter or word would be left with no partner, so no pairing can exist.
Check the letter against its earlier word
Walk the pairs (letter, word) together. If letter is already in letter_to_word with a different word, return false, because one letter would then stand for two words.
Check the word against its earlier letter
If word is already in word_to_letter with a different letter, return false, because two letters would then share one word.
Record the pair both ways
Set letter_to_word[letter] = word and word_to_letter[word] = letter. When the pair is already known, writing it again changes nothing, so no extra branch is needed.
Why surviving the loop means true
Every pair either matched both maps or added a new pair to both, so at the end the two maps are exact mirrors of each other. Mirrored maps are a one-to-one mapping, so return true.
Code in Python, C++ and Java
s on spaces. The counts are equal, so every letter has exactly one word beside it. The dashed shapes below are the distinct letters and words, not yet paired.s on spaces. The counts are equal, so every letter has exactly one word beside it. The dashed shapes below are the distinct letters and words, not yet paired.s on spaces. The counts are equal, so every letter has exactly one word beside it. The dashed shapes below are the distinct letters and words, not yet paired.Common pitfalls
Keeping only the letter-to-word map
if letter_to_word.get(letter, word) != word:
return False
letter_to_word[letter] = wordif letter_to_word.get(letter, word) != word:
return False
if word_to_letter.get(word, letter) != letter:
return FalseWith pattern = "abba" and s = "dog dog dog dog", letter a always meets dog and letter b always meets dog, so the one map never complains and the code returns true. The answer is false: a and b share a word, and only the reverse map catches it.
Pairing with zip before checking the counts
for letter, word in zip(pattern, words):
...
return Trueif len(words) != len(pattern):
return Falsezip stops at the shorter input without warning. For pattern = "aaa" and s = "dog dog dog dog" it pairs only three words, all consistent, and returns true; the fourth dog has no letter, so the answer is false. In C++ or Java the missing check reads past the end of the shorter array instead.
Complexity
pattern and m is the length of s. Splitting reads every character of s once, and each of the n pairs costs one lookup per map, where hashing a word costs its length. The words list and the maps hold at most m characters of words plus up to 26 letters.Word Pattern FAQ
How is this different from Isomorphic Strings?
The rule is the same one-to-one pairing, but here the right side is whole words. You split s first, the two sides can have different counts, and one map is keyed by strings. Isomorphic Strings pairs two equal-length strings character by character.
Why does my Java solution fail only on long inputs?
A popular short version compares the old indices returned by map.put(c, i) and map.put(w, i) with !=. Those are Integer objects, and Java only shares one object per value from -128 to 127. From index 128 on, two equal indices are different objects, so != reports a mismatch: 130 copies of a against 130 copies of dog returns false. Compare with Objects.equals, or use the two-map version on this page.
What changes in Word Pattern II?
In Word Pattern II, s has no spaces, so you must also decide where each word ends. That turns the one pass into backtracking: try every possible next word for the current letter, keep the same two maps, and undo a pairing when a later letter fails.