Find and Replace Pattern

You are given a list of strings `words` and a string `pattern`. Return the words that **match** the pattern. You may return the answer in **any order**. A word matches the pattern if there is a permutation of letters `p` such that replacing every letter `x` in the pattern with `p(x)` turns the pattern into the word. In other words, the letters must correspond one to one: every letter of the pattern maps to exactly one letter of the word, and no two pattern letters map to the same word letter.

30:00

Find and Replace Pattern
medium
Free written solution
Topics
Companies

You are given a list of strings words and a string pattern. Return the words that match the pattern. You may return the answer in any order.

A word matches the pattern if there is a permutation of letters p such that replacing every letter x in the pattern with p(x) turns the pattern into the word.

In other words, the letters must correspond one to one: every letter of the pattern maps to exactly one letter of the word, and no two pattern letters map to the same word letter.

Example 1:
Input: {"words":["abc","deq","mee","aqq","dkd","ccc"],"pattern":"abb"}
Output: ["mee","aqq"]
Constraints:
  • 1≤pattern.length≤201 \leq \text{pattern.length} \leq 20

  • 1≤words.length≤501 \leq \text{words.length} \leq 50

  • words[i].length == pattern.length

  • pattern and words[i] are lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["abc","deq","mee","aqq","dkd","ccc"],"pattern":"abb"}

A word matches "abb" when its letters pair with the pattern's letters one to one. Two maps catch both ways a pairing can break.

pattern

w

│
│
│

p

a
b
b

word → pattern

empty

pattern → word

empty

words

abc
deq
mee
aqq
dkd
ccc
position agrees / match
position being checked
pairing broken
Variables
VariableValue
matched0
DepthFunction Call
Stack empty
0/30