Check if string follows order of characters defined by a pattern or not | Set 2
Last Updated :
01 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.
Another solution to the same problem is posted here.
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.
The idea here is to reduce the given string to the pattern given. For characters given in the pattern, we only keep the corresponding characters in the string. In the new string, we delete continuous repeated characters. The modified string should then be equal to the pattern given. Lastly, we compare modified string to the pattern given and return true of false accordingly.
Illustration:
str = "bfbaeadeacc", pat[] = "bac"
1) Remove extra characters from str (characters
that are not present in pat[]
str = "bbaaacc" [f, e and d are removed]
3) Removed consecutive repeating occurrences of
characters
str = "bac"
4) Since str is same as pat[], we return true
Below is implementation of above steps.
C++
// C++ code for the above approach
#include <iostream>
#include <unordered_set>
using namespace std;
bool followsPattern(string str, string pattern) {
// Insert all characters of pattern in a hash set
unordered_set<char> patternSet;
for (int i = 0; i < pattern.length(); i++) {
patternSet.insert(pattern[i]);
}
// Build modified string (string with characters only from pattern are taken)
string modifiedStr = str;
for (int i = str.length() - 1; i >= 0; i--) {
if (patternSet.find(str[i]) == patternSet.end()) {
modifiedStr.erase(i, 1);
}
}
// Remove more than one consecutive occurrences of pattern characters from modified string
for (int i = modifiedStr.length() - 1; i > 0; i--) {
if (modifiedStr[i] == modifiedStr[i - 1]) {
modifiedStr.erase(i, 1);
}
}
// After above modifications, the length of modified string must be same as pattern length
if (pattern.length() != modifiedStr.length()) {
return false;
}
// And pattern characters must also be same as modified string characters
for (int i = 0; i < pattern.length(); i++) {
if (pattern[i] != modifiedStr[i]) {
return false;
}
}
return true;
}
int main() {
string str = "engineers rock";
string pattern = "er";
cout << "Expected: true, Actual: " << followsPattern(str, pattern) << endl;
str = "engineers rock";
pattern = "egr";
cout << "Expected: false, Actual: " << followsPattern(str, pattern) << endl;
str = "engineers rock";
pattern = "gsr";
cout << "Expected: false, Actual: " << followsPattern(str, pattern) << endl;
str = "engineers rock";
pattern = "eger";
cout << "Expected: true, Actual: " << followsPattern(str, pattern) << endl;
return 0;
}
// This code is contributed by adityashatmfh
Java
// Java program to check if characters of a string follow
// pattern defined by given pattern.
import java.util.*;
public class OrderOfCharactersForPattern
{
public static boolean followsPattern(String str, String pattern)
{
// Insert all characters of pattern in a hash set,
Set<Character> patternSet = neHashSet<>();
for (int i=0; i<pattern.length(); i++)
patternSet.add(pattern.charAt(i));
// Build modified string (string with characters only from
// pattern are taken)
StringBuilder modifiedString = new StringBuilder(str);
for (int i=str.length()-1; i>=0; i--)
if (!patternSet.contains(modifiedString.charAt(i)))
modifiedString.deleteCharAt(i);
// Remove more than one consecutive occurrences of pattern
// characters from modified string.
for (int i=modifiedString.length()-1; i>0; i--)
if (modifiedString.charAt(i) == modifiedString.charAt(i-1))
modifiedString.deleteCharAt(i);
// After above modifications, the length of modified string
// must be same as pattern length
if (pattern.length() != modifiedString.length())
return false;
// And pattern characters must also be same as modified string
// characters
for (int i=0; i<pattern.length(); i++)
if (pattern.charAt(i) != modifiedString.charAt(i))
return false;
return true;
}
// Driver program
int main()
{
String str = "engineers rock";
String pattern = "er";
System.out.println("Expected: true, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "egr";
System.out.println("Expected: false, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "gsr";
System.out.println("Expected: false, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "eger";
System.out.println("Expected: true, Actual: " +
followsPattern(str, pattern));
return 0;
}
}
Python3
# Python3 program to check if characters of
# a string follow pattern defined by given pattern.
def followsPattern(string, pattern):
# Insert all characters of pattern in a hash set,
patternSet = set()
for i in range(len(pattern)):
patternSet.add(pattern[i])
# Build modified string (string with characters
# only from pattern are taken)
modifiedString = string
for i in range(len(string) - 1, -1, -1):
if not modifiedString[i] in patternSet:
modifiedString = modifiedString[:i] + \
modifiedString[i + 1:]
# Remove more than one consecutive occurrences
# of pattern characters from modified string.
for i in range(len(modifiedString) - 1, 0, -1):
if modifiedString[i] == modifiedString[i - 1]:
modifiedString = modifiedString[:i] + \
modifiedString[i + 1:]
# After above modifications, the length of
# modified string must be same as pattern length
if len(pattern) != len(modifiedString):
return False
# And pattern characters must also be same
# as modified string characters
for i in range(len(pattern)):
if pattern[i] != modifiedString[i]:
return False
return True
# Driver Code
if __name__ == "__main__":
string = "engineers rock"
pattern = "er"
print("Expected: true, Actual:",
followsPattern(string, pattern))
string = "engineers rock"
pattern = "egr"
print("Expected: false, Actual:",
followsPattern(string, pattern))
string = "engineers rock"
pattern = "gsr"
print("Expected: false, Actual:",
followsPattern(string, pattern))
string = "engineers rock"
pattern = "eger"
print("Expected: true, Actual:",
followsPattern(string, pattern))
# This code is contributed by
# sanjeev2552
C#
// C# program to check if characters of a string follow
// pattern defined by given pattern.
using System;
using System.Collections.Generic;
using System.Text;
class GFG
{
public static bool followsPattern(String str, String pattern)
{
// Insert all characters of pattern in a hash set,
HashSet<char> patternSet = new HashSet<char>();
for (int i = 0; i < pattern.Length; i++)
patternSet.Add(pattern[i]);
// Build modified string (string with characters
// only from pattern are taken)
StringBuilder modifiedString = new StringBuilder(str);
for (int i = str.Length - 1; i >= 0; i--)
if (!patternSet.Contains(modifiedString[i]))
modifiedString.Remove(i, 1);
// Remove more than one consecutive occurrences of pattern
// characters from modified string.
for (int i = modifiedString.Length - 1; i > 0; i--)
if (modifiedString[i] == modifiedString[i - 1])
modifiedString.Remove(i, 1);
// After above modifications, the length of modified string
// must be same as pattern length
if (pattern.Length != modifiedString.Length)
return false;
// And pattern characters must also be same
// as modified string characters
for (int i = 0; i < pattern.Length; i++)
if (pattern[i] != modifiedString[i])
return false;
return true;
}
// Driver program
public static void Main(String[] args)
{
String str = "engineers rock";
String pattern = "er";
Console.WriteLine("Expected: true, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "egr";
Console.WriteLine("Expected: false, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "gsr";
Console.WriteLine("Expected: false, Actual: " +
followsPattern(str, pattern));
str = "engineers rock";
pattern = "eger";
Console.WriteLine("Expected: true, Actual: " +
followsPattern(str, pattern));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to check if characters of a string follow
// pattern defined by given pattern.
function followsPattern(str, pattern)
{
// Insert all characters of pattern in a hash set,
let patternSet = new Set();
for (let i=0; i<pattern.length; i++)
patternSet.add(pattern[i]);
// Build modified string (string with characters only from
// pattern are taken)
let modifiedString = (str).split("");
for (let i=str.length-1; i>=0; i--)
if (!patternSet.has(modifiedString[i]))
modifiedString.splice(i,1);
// Remove more than one consecutive occurrences of pattern
// characters from modified string.
for (let i=modifiedString.length-1; i>0; i--)
if (modifiedString[i] == modifiedString[i-1])
modifiedString.splice(i,1);
// After above modifications, the length of modified string
// must be same as pattern length
if (pattern.length != modifiedString.length)
return false;
// And pattern characters must also be same as modified string
// characters
for (let i=0; i<pattern.length; i++)
if (pattern[i] != modifiedString[i])
return false;
return true;
}
// Driver program
let str = "engineers rock";
let pattern = "er";
document.write("Expected: true, Actual: " +
followsPattern(str, pattern)+"<br>");
str = "engineers rock";
pattern = "egr";
document.write("Expected: false, Actual: " +
followsPattern(str, pattern)+"<br>");
str = "engineers rock";
pattern = "gsr";
document.write("Expected: false, Actual: " +
followsPattern(str, pattern)+"<br>");
str = "engineers rock";
pattern = "eger";
document.write("Expected: true, Actual: " +
followsPattern(str, pattern)+"<br>");
// This code is contributed by rag2127
</script>
Output:
Expected: true, Actual: true
Expected: false, Actual: false
Expected: false, Actual: false
Expected: true, Actual: true
Time Complexity: Time complexity of above implementations is actually O(mn + n^2) as we use deleteCharAt() to remove characters. We can optimize above solution to work in linear time. Instead of using deleteCharAr(), we can create an empty string and add only required characters to it.
StringBuilder is used to operate on input string. This is because StringBuilder is mutable, while String is immutable object. To create a new string takes O(n) space, so extra space is O(n).
We have discussed two more 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 3
Similar Reads
Check if string follows order of characters defined by a pattern or not | Set 3
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 t
7 min read
Check if string follows order of characters defined by a pattern or not | Set 1
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 Explanation:
8 min read
Check if a string follows a^nb^n pattern or not
Given string str, return true string follows pattern anbn, i.e., it has a's followed by b's such that the number of a's and b's are same. Examples: Input : str = "aabb" Output : Yes Input : str = "abab" Output : No Input : str = "aabbb" Output : No The idea is to first count a's. If number of a's is
8 min read
Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (long
6 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
5 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" sat
5 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the res
3 min read
Check if the characters in a string form a Palindrome in O(1) extra space
Given string str. The string may contain lower-case letters, special characters, digits, or even white spaces. The task is to check whether only the letters present in the string are forming a Palindromic combination or not without using any extra space. Note: It is not allowed to use extra space to
10 min read
Python | Check order of character in string using OrderedDict( )
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: trueExplanation: All
3 min read
Check if a string consists only of special characters
Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print âYesâ. Otherwise, print âNoâ. Examples: Input: str = â@#$&%!~âOutput: YesExplanation: Given string contains only special char
9 min read