Find and Replace Pattern - Problem
Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
Input & Output
Example 1 — Basic Pattern Matching
$
Input:
words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
›
Output:
["mee","aqq"]
💡 Note:
"mee" matches pattern "abb" (m→a, e→b), and "aqq" matches (a→a, q→b). Both have the same structure where first char differs from second and third chars which are same.
Example 2 — No Matches
$
Input:
words = ["a","b","c"], pattern = "aa"
›
Output:
[]
💡 Note:
No single character word can match pattern "aa" which requires two identical characters.
Example 3 — All Different Pattern
$
Input:
words = ["abc","cab","xyz"], pattern = "abc"
›
Output:
["abc","cab","xyz"]
💡 Note:
Pattern "abc" means all characters different. All three words have distinct characters so they all match.
Constraints
- 1 ≤ words.length ≤ 50
- 1 ≤ pattern.length ≤ 20
- 1 ≤ words[i].length ≤ 20
- words[i] and pattern consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Words list and pattern to match against
2
Process
Check each word for bijective character mapping
3
Output
List of words that match the pattern
Key Takeaway
🎯 Key Insight: Use bidirectional hash maps to ensure bijective character mapping between pattern and word
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code