#890
Find and Replace Pattern
MediumArrayHash TableString
Approaches
💡
Intuition
Time Space
We can check each word against the pattern by creating a mapping of characters in the pattern to characters in the word. If we can establish a one-to-one mapping for all characters, the word matches the pattern.
⚙️
Algorithm
5 steps- 1Step 1: For each word in the list, check if its length matches the pattern's length.
- 2Step 2: Create two dictionaries: one to map characters from the pattern to the word and another to map characters from the word to the pattern.
- 3Step 3: Iterate through the characters of the pattern and the word simultaneously, updating the dictionaries.
- 4Step 4: If a character mapping is inconsistent (i.e., a character in the pattern maps to different characters in the word), the word does not match.
- 5Step 5: If all characters can be mapped consistently, add the word to the result list.
solution.py13 lines
1def findAndReplacePattern(words, pattern):
2 def matches(word):
3 if len(word) != len(pattern): return False
4 p_to_w, w_to_p = {}, {}
5 for p_char, w_char in zip(pattern, word):
6 if p_char not in p_to_w:
7 p_to_w[p_char] = w_char
8 if w_char not in w_to_p:
9 w_to_p[w_char] = p_char
10 if p_to_w[p_char] != w_char or w_to_p[w_char] != p_char:
11 return False
12 return True
13 return [word for word in words if matches(word)]Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.