Similar Problems

Similar Problems not available

Find And Replace Pattern - Leetcode Solution

Companies:

LeetCode:  Find And Replace Pattern Leetcode Solution

Difficulty: Medium

Topics: string hash-table array  

Problem: Find and Replace Pattern

Description: 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.

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.

Example 2: Input: words = ["a","b","c"], pattern = "a" Output: ["a","b","c"]

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

Solution: To solve this problem, we need to iterate over each word in the list of words, and check if a permutation exists between the letters of the pattern and the letters of the word.

Steps:

  1. Define a function isMatch(word, pattern) that takes in a word and pattern and returns True if a permutation exists between the letters of the pattern and the letters of the word and False otherwise.
  2. Iterate over each word in the list of words and check if it matches the pattern using the isMatch function.
  3. If the word matches the pattern, append it to the output list.
  4. Return the output list.

Code:

def isMatch(word, pattern): if len(word) != len(pattern): return False

char_map = {}
for i in range(len(word)):
    if pattern[i] not in char_map:
        if word[i] in char_map.values():
            return False
        char_map[pattern[i]] = word[i]
    elif char_map[pattern[i]] != word[i]:
        return False
    
return True

def findAndReplacePattern(words, pattern): output = [] for word in words: if isMatch(word, pattern): output.append(word)

return output

Test the solution with the examples given in the problem statement

words = ["abc","deq","mee","aqq","dkd","ccc"] pattern = "abb" print(findAndReplacePattern(words, pattern)) # ["mee","aqq"]

words = ["a","b","c"] pattern = "a" print(findAndReplacePattern(words, pattern)) # ["a","b","c"]

Find And Replace Pattern Solution Code

1