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
Find and Replace Pattern OverviewInput:words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"], pattern = "abb"Pattern Analysis:"abb" structure→ First char different, second and third sameWord Matching:"abc" ✗"deq" ✗"mee" ✓"aqq" ✓"dkd" ✗"ccc" ✗Output:["mee", "aqq"]🎯 Key: Bijective mapping ensures each pattern char maps to unique word char
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
Asked in
Google 15 Facebook 12 Amazon 8
89.2K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen