← Questions

Match words against a letter pattern

0
MetaCoding

A coding interview question asked at Meta. It tests hash map, strings and bijection.

Given a pattern string and a list of words, decide for each word whether it follows the pattern.

A word follows the pattern when it has the same length as the pattern and the letters line up through a one-to-one correspondence:

  • every occurrence of a given pattern letter lines up with the same word letter, and
  • two different pattern letters never line up with the same word letter.

Implement:

def match_words(pattern: str, words: list[str]) -> list[bool]:
    ...

Return a list of booleans, one per word, in input order.

Constraints

  • 0 <= len(pattern) <= 10^4, 0 <= len(words) <= 10^4
  • Strings may contain any characters; treat each character as a symbol.
  • Aim for time linear in the total number of characters.

Example 1

pattern = "abba"
words   = ["xyyx", "xxxx", "qrrq", "xyzx", "xyy"]
output  = [True, False, True, False, False]

"xxxx" fails because a and b would both map to x. "xyy" fails because the lengths differ.

Example 2

pattern = "abc"
words   = ["cab", "dee", "xyz"]
output  = [True, False, True]

Be ready to extend this: patterns whose letters stand for whole words in a sentence, grouping a dictionary by shape, and letters that stand for substrings of unknown length.

Clarifying questions

  • Is the comparison case-sensitive?
  • Does an empty pattern match only the empty word?
  • Is the mapping built fresh for each word? (Yes: words do not share mappings.)

What a strong answer covers

  • For each word: checks the length first, then builds two maps, pattern letter to word letter and word letter to pattern letter, and fails on the first conflict.
  • Or computes a "shape" (each character replaced by the index of its first occurrence) for the pattern once and for each word, and compares shapes. Both are linear in the total number of characters.
  • Explains why one map is not enough: against "abba", "xxxx" passes a pattern-to-word check alone (a and b both map to x); only the reverse map catches it.
  • Edge cases: different lengths, empty strings, non-letter characters, and the same word appearing twice.
  • Tests the examples, plus a word that fails only in the reverse direction.

Follow-ups

  • Pattern letters stand for whole words in a sentence (split on spaces, then the same two-map check).
  • Group a dictionary by shape with a hash map from shape to words.
  • Pattern letters stand for substrings of unknown length: backtracking, which is exponential, and how lengths prune it.

Where it's asked

What it tests

hash map · strings · bijection

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding