← Questions

Match words against a letter pattern

0
MetaCoding

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.

Reconstructed from the reported question; details may differ from what interviewers ask.

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