LeetCode #290 Easy

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.

Constraints
  • 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.
hash mapstringbijection
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def wordPattern(self, pattern: str, s: str) -> bool:
▶3 words = s.split()
▶4 if len(words) != len(pattern):
▶5 return False
▶6 letter_to_word = {}
▶7 word_to_letter = {}
▶8 for letter, word in zip(pattern, words):
▶9 if letter_to_word.get(letter, word) != word:
▶10 return False
▶11 if word_to_letter.get(word, letter) != letter:
▶12 return False
▶13 letter_to_word[letter] = word
▶14 word_to_letter[word] = letter
▶15 return True
patternwordsadogbcatbcatadogletterword4 letters, 4 words → counts match
letters4
words4
Split 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.
patternwordsadogbcatbcatadogi = 0letterwordadognew pair: a ↔ dog
letter → worda→dog
word → letterdog→a
Neither a nor dog is taken yet, so both checks pass. Store the pair in both maps; the link stands for both entries.
patternwordsadogbcatbcatadogi = 1letterwordabdogcatnew pair: b ↔ cat
letter → worda→dog, b→cat
word → letterdog→a, cat→b
Neither b nor cat is taken yet, so both checks pass. Store the pair in both maps; the link stands for both entries.
patternwordsadogbcatbcatadogi = 2letterwordabdogcatb and cat are already paired → agree
letter → worda→dog, b→cat
word → letterdog→a, cat→b
Both maps already hold this exact pair, so it repeats an existing promise and breaks nothing. Move on.
patternwordsadogbcatbcatadogi = 3letterwordabdogcata and dog are already paired → agree
letter → worda→dog, b→cat
word → letterdog→a, cat→b
Both maps already hold this exact pair, so it repeats an existing promise and breaks nothing. Move on.
patternwordsadogbcatbcatadogletterwordabdogcatevery pair agreed → true
letter → worda→dog, b→cat
word → letterdog→a, cat→b
Each letter links to exactly one word and each word to exactly one letter, so the sentence follows the pattern.
05

Common pitfalls

Keeping only the letter-to-word map

✗ Wrong
if letter_to_word.get(letter, word) != word:
    return False
letter_to_word[letter] = word
✓ Right
if letter_to_word.get(letter, word) != word:
    return False
if word_to_letter.get(word, letter) != letter:
    return False

With 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

✗ Wrong
for letter, word in zip(pattern, words):
    ...
return True
✓ Right
if len(words) != len(pattern):
    return False

zip 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.

06

Complexity

Time
O(n + m)
Space
O(n + m)
n is the length of 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.
07

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.