Leetcode - Find and Replace Pattern Solution
1 min read

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]

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×