Problem Description
Given a list of words and a string pattern, return the list of words that match the pattern. A word matches the pattern if there exists a bijective mapping (permutation) of letters from the pattern to the word such that replacing every letter in the pattern with its mapped letter returns the word.
Key Insights
- The mapping between letters must be one-to-one and onto (bijective).
- Use two hash maps (or dictionaries): one mapping from the pattern to the word and another from the word to the pattern.
- For each word, iterate through each character position and verify that both mappings are consistent.
- If a conflict is detected in either mapping, the word does not match the pattern.
Space and Time Complexity
Time Complexity: O(n * m), where n is the number of words and m is the length of the pattern.
Space Complexity: O(m) per word, used for the bidirectional mappings.
Solution
For each word, use a helper function to build two mappings: one from the pattern to the word and one from the word to the pattern. Check character by character that:
- If a mapping from a pattern character already exists, it matches the corresponding word character.
- If a mapping from a word character already exists, it matches the corresponding pattern character. If both conditions hold for all characters, the word matches the pattern. Otherwise, it does not.