DSA Factory
Free Hashing lessonsHashing · Stage 1 · Grouping by key · Step 3

Letters to words

Check that a sentence follows a pattern like "abba". About 9 minutes.

Letters stand for words

The pattern "abba" and the sentence "dog cat cat dog" match: a stands for dog, b for cat. It's the renaming from the last step, except each letter now stands for a whole word.

Split the sentence into words, then pair each pattern letter with the word in the same position. Keep two maps again, letter to word and word to letter, so no letter has two words and no word has two letters.

Two maps again: letter to word, and word to letter.
pattern = "abba", s = "dog cat cat dog"
letter
a
b
b
a
word
dog
cat
cat
dog

4 letters and 4 words: the counts match, so it's worth checking.

Move 1 of 5

Check the counts first

If the number of words doesn't equal the number of letters, some letter has no word, or some word has no letter. There's no need to look further: the answer is no.

"dog dog dog dog" doesn't follow "abba": a and b would both stand for dog.

Different counts: can't match: return false straight away.
In code
words = s.split()
if len(words) != len(pattern):
    return False
to_word, to_letter = {}, {}
for ch, w in zip(pattern, words):
    if to_word.get(ch, w) != w:
        return False
    if to_letter.get(w, ch) != ch:
        return False
    to_word[ch], to_letter[w] = w, ch
return True
Quick check

Does "dog dog dog dog" follow the pattern "abba"?

  1. ANo
  2. BYes
  3. CNo, the lengths differ
Show the answer

No. a and b would both stand for dog.

Your problem

Follows the pattern?

You get a pattern of lowercase letters and a sentence of words separated by single spaces. Return true if there is a one-to-one match between letters and words so that the sentence follows the pattern.

Example
pattern = "abba", s = "dog cat cat dog" → true

0 ≤ pattern length ≤ 300 · 0 ≤ s length ≤ 3,000 · single spaces, none at the ends

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve