VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-string-follows-order-of-characters-defined-by-a-pattern-or-not-set-3/

⇱ Check if string follows order of characters defined by a pattern or not | Set 3 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if string follows order of characters defined by a pattern or not | Set 3

Last Updated : 20 Mar, 2023

Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern.

Examples: 

Input: string = "engineers rock", pattern = "er";
Output: true
All 'e' in the input string are before all 'r'.

Input: string = "engineers rock", pattern = "egr";
Output: false
There are two 'e' after 'g' in the input string.

Input: string = "engineers rock", pattern = "gsr";
Output: false
There are one 'r' before 's' in the input string.

We have discussed two approaches to solve this problem. 
Check if string follows order of characters defined by a pattern or not | Set 1 
Check if string follows order of characters defined by a pattern or not | Set 2

In this approach we first assign a label (or order) to characters of pattern. The labels are assigned in increasing order. 

For example, the pattern "gsr" is labeled as following 

"g" => 1
"s" => 2
"r" => 3

It means 'g' will come first, then 's', then 'r'
After assigning labels to pattern characters, we iterate through string characters. While traversing, we keep track of label (or order) of last visited character. If label of current character is less than previous character, we return false. Otherwise we update last label. If all characters follow order, we return true.

Below is the implementation 


Output
false

Time Complexity of this program is O(n) with constant extra space (the array label is of constant size, 256).

Auxiliary Space: O(256).

Comment
Article Tags:
Article Tags: