All problems

Find and Replace Pattern

Medium · hash map

You are given a list of lower-case words and a lower-case pattern. Every word has the same length as the pattern.

A word matches the pattern if you can swap each letter of the pattern for a letter so that you get exactly that word, where the swap follows two rules:

For example, the pattern "xyx" matches "pop" (x becomes p, y becomes o), but not "aaa", because x and y would both have to become a, and not "fee", because the first x would become f and the second e.

Return the words that match, in the order they appear in words. A word that appears more than once is returned once for each appearance. If no word matches, return an empty list.

Examples

Example 1

Input: words = ["pop", "sos", "fee", "aaa", "dad"], pattern = "xyx"

Output: ["pop", "sos", "dad"]

"fee" and "aaa" break the rules: the first needs x to become two different letters, and the second makes x and y become the same letter.

Example 2

Input: words = ["xyz", "xxy", "pqr", "aba"], pattern = "abc"

Output: ["xyz", "pqr"]

The pattern has three different letters, so a matching word needs three different letters.

Example 3

Input: words = ["bb", "bc", "zz"], pattern = "aa"

Output: ["bb", "zz"]

Constraints