Given a string and a pattern (having all distinct characters), determine whether the string characters follow a specific order as defined by the pattern’s characters.

For example,

Input:
 
word = Techie Delight
pattern = el
 
Output: Pattern found
 
The pattern characters follow the order [e, e, e, l] in the input string. Note that all e’s appear before l.
 
 
Input:
 
word = Techie Delight
pattern = ei
 
Output: Pattern not found
 
The pattern characters follow the order [e, i, e, e, i] in the input string. Note that all e’s doesn’t appear before all i’s.

Practice this problem

The idea is to loop through all characters of the pattern. If at any point, the last occurrence of the previous encountered character is after the first occurrence of the current character in the input string, we can say that the string doesn’t follow the order defined by the pattern.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

Pattern found

Java


Download  Run Code

Output:

Pattern found

Python


Download  Run Code

Output:

Pattern found

The time complexity of the above solution is O(m.n), where m is the length of the string and n is the length of the pattern. The auxiliary space required by the program is O(1).

 
Here’s another simple approach to solving this problem. The solution can be divided into three steps:

  1. Remove all characters from the given string that are not present in the specified pattern.
  2. Remove the adjacent duplicates from the modified string.
  3. Compare the resultant string with the pattern and return true if both are equal.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Pattern found

Java


Download  Run Code

Output:

Pattern found

Python


Download  Run Code

Output:

Pattern found