Imagine you're a code-breaking detective! 🕵️♀️ You have a secret pattern and a list of words, and you need to find which words could be the result of applying a secret cipher to your pattern.
Here's the twist: the cipher is a bijection - each letter in the pattern maps to exactly one letter in the word, and no two pattern letters can map to the same word letter. It's like a perfect one-to-one substitution cipher!
For example:
• Pattern: "abb"
• Word: "mee"
• Mapping: a→m, b→e ✅ Valid!
• Word: "mff"
• Mapping: a→m, b→f ✅ Valid!
• Word: "mef"
• Would need: a→m, b→e, b→f ❌ Invalid! (b can't map to both e and f)
Your mission: Return all words from the input list that match the given pattern according to these cipher rules.
Input & Output
Visualization
Time & Space Complexity
Where n is the number of words and m is the length of each word. We process each character exactly once.
We need space for two hash maps, each storing at most m key-value pairs (the length of the pattern).
Constraints
- 1 ≤ words.length ≤ 50
- 1 ≤ words[i].length ≤ 20
- words[i] and pattern consist of lowercase English letters
- words[i].length == pattern.length