Leetcode - Find and Replace Pattern Solution

You have a list of words and a pattern, and you want to know which words in words matches the pattern.

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.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.

Example 1:

Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. 
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.

Note:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

Solution in Python

class Solution:
    @staticmethod
    def recreate(word):
        word_map = defaultdict(int)
        recreated_word = 0
        index = 0
        for j,i in enumerate(word):
            key_index = word_map.get(i)
            if not key_index:
                index+=1
                word_map[i] = index
            recreated_word +=((10**j)*word_map[i])

        return recreated_word
        
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        recreated_pattern = self.recreate(pattern)
        return [word for word in words if self.recreate(word) == recreated_pattern]

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe