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 <= pattern.length <= 201 <= words.length <= 50words[i].length == pattern.lengthpattern and words[i] are lowercase English letters.In this approach, we establish a one-to-one mapping for each letter in the pattern to letters in each word. To do this, we use two maps or dictionaries: one for mapping pattern to word letters and another for mapping word to pattern letters. Both maps are used to ensure that the mapping is bijective (i.e., one-to-one).
This C code defines a function matchesPattern to check if a particular word matches the pattern based on bijective mappings. The primary function findAndReplacePattern iterates over each word, using matchesPattern to verify matches, and stores the matching words.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n * m), where n is the number of words and m is the word length.
Space Complexity: O(m), for the maps storing character mappings.
In this approach, we map each character of the string to its first occurrence index in the string. This creates a unique encoding pattern for comparison. Two strings match if they have the same encoding pattern.
This C program calculates an encoded representation for the pattern and each word using indices of first occurrences. It then compares these encodings to determine if a word matches the pattern.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n * m), where n is the number of words and m is the word length.
Space Complexity: O(m), for storing encoded strings and maps.
| Approach | Complexity |
|---|---|
| Bijective Mapping Approach | Time Complexity: O(n * m), where n is the number of words and m is the word length. |
| Pattern Encoding Approach | Time Complexity: O(n * m), where n is the number of words and m is the word length. |
8 patterns to solve 80% Leetcode problems • Sahil & Sarra • 656,571 views views
Watch 9 more video solutions →Practice Find and Replace Pattern with our built-in code editor and test cases.
Practice on FleetCode