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 INPUT words array: "abc" "deq" "mee" "aqq" "dkd" "ccc" pattern: "abb" Pattern structure: a-b-b 1st char unique 2nd, 3rd same Normalized: [0,1,1] a=0, b=1 ALGORITHM STEPS 1 Normalize Pattern "abb" --> [0,1,1] 2 Normalize Each Word Map chars to indices 3 Compare Signatures Match normalized forms 4 Collect Matches Return matching words Normalization Results: "abc" --> [0,1,2] NO "deq" --> [0,1,2] NO "mee" --> [0,1,1] OK "aqq" --> [0,1,1] OK "dkd" --> [0,1,0] NO "ccc" --> [0,0,0] NO FINAL RESULT Matched Words: "mee" m=a, e=b "aqq" a=a, q=b Bijection Mapping: mee: m --> a e --> b aqq: a --> a q --> b Output: ["mee", "aqq"] Key Insight: Hash Map Normalization Convert each word to a normalized signature by mapping each unique character to its first occurrence index. Two words match the same pattern if and only if they have identical normalized signatures. This ensures a bijective (one-to-one) character mapping exists. TutorialsPoint - Find and Replace Pattern | Hash Map Normalization Approach
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