Match words against a letter pattern
I was asked this
No reports yet. Sign in to say where you were asked it.
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
