Given a list of words and a pattern, find all words in the list that follows the same order of characters as that of the pattern.

For example,

Input:
 
list = [leet, abcd, loot, geek, cool, for, peer, dear, seed, meet, noon, otto, mess, loss]
 
pattern = moon (pattern is 4 digits with distinct character at first and last index, and same character at 1st and 2nd index)
 
Output: [leet, loot, geek, cool, peer, seed, meet]
 
 
Input:
 
list = [leet, abcd, loot, geek, cool, for, peer, dear, seed, meet, noon, otto, mess, loss]
 
pattern = pqrs (pattern is 4 digits and has all distinct characters)
 
Output: [abcd, dear]

Practice this problem

We can use hashing to solve this problem. The idea is to use a map and associate each distinct character of the given word with the corresponding character in the pattern and store it. For each character in both word and the pattern, if the character is seen before, it should only be mapped to the corresponding character in the pattern. Note that we also have to associate each character in the given pattern with the corresponding character in the given word and follow the same process.

Let’s understand this by taking an example. Consider the word 'moon' and the pattern 'noon'. We will process each character in both word and pattern. Let’s check for mapping from the given word to the given pattern.

(m, n) —> As m is seen for the first time, map m to n.
 
(o, o) —> As o is seen for the first time, map o to o.
 
(o, o) —> As o is seen before, and it is already mapped to o, which is the same as current character in pattern o.
 
(n, n) —> As n is seen for the first time, map n to n.

So, mapping from the given word to the given pattern is good. Now let’s check mapping from the pattern to the word.

(n, m) —> As n is seen for the first time, map n to m.
 
(o, o) —> As o is seen for the first time, map o to o.
 
(o, o) —> As o is seen before, and it is already mapped to o, which is the same as current character in pattern o.
 
(n, n) —> As n is seen before, and it is already mapped to m, which is different from the current character in pattern n.

So, mapping from the given pattern to the given word fails, and we can say that the pattern doesn’t match the word. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

leet loot geek cool peer seed meet

Java


Download  Run Code

Output:

leet loot geek cool peer seed meet

Python


Download  Run Code

Output:

leet loot geek cool peer seed meet

The time complexity of the above solution is O(n.m), where n is the total number of words and m is the pattern’s length.