Match words against a letter pattern
I was asked this
No reports yet. Sign in to say where you were asked it.
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 (aandbboth map tox); 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
