Wildcard Pattern Matching
Last Updated :
17 Sep, 2024
Given a text t and a wildcard pattern p, implement wildcard pattern matching algorithm that finds if wildcard pattern is matched with text. The matching should cover the entire text (not partial text). The wildcard pattern can include the characters ‘?’ and ‘*’
- ‘?’ â matches any single character
- ‘*’ â Matches any sequence of characters (including the empty sequence)
Input : t = “abcde”, p = “a?c*”
Output : Yes
Explanation : ? matches with b and * matches with “de”
Input : t = “abcde”, p = “e?c*”
Output : No
Input : t = “abc”, p = “*”
Output : Yes

Naive Recursive Solution
We begin matching from the last characters of the both pattern and text. The following cases arise.
Case 1: The character is â*â . Here two cases arises as follows:
- We can ignore â*â character and move to next character in the Pattern.
- We match ‘*’ with one or more characters in Text. Here we will move to next in the text.
Case 2: The character is â?â
We ignore current character in text and move to next character in the Pattern and Text.
Case 3: The character is not a wildcard character
If current character in Text matches with current character in Pattern, we move to next character in the Pattern and Text. If they do not match, we return false.
Below is a simple recursive solution based on this idea.
C++
#include <iostream>
#include <string>
using namespace std;
// n is the length of text t
// m is the length of patter p
bool smRec(string t, string p, int n, int m)
{
// empty pattern can only match with
// empty string
if (m == 0)
return (n == 0);
// Empty string can match only with
// one or more occurrences of '*'
if (n == 0)
{
for (int i = 0; i < m; i++)
if (p[i] != '*')
return false;
return true;
}
// Either the last characters match or pattern
// has '?'
if (t[n - 1] == p[m - 1] || p[m - 1] == '?')
return smRec(t, p, n - 1, m - 1);
// If last character is '*', two cases arise
// 1) We ignore it
// 2) We match it with a character
if (p[m - 1] == '*')
return smRec(t, p, n, m - 1) ||
smRec(t, p, n - 1, m);
return false;
}
// Wrapper over the above method
bool isMatch(string t, string p)
{
return smRec(t, p, t.size(), p.size());
}
int main()
{
string t = "abcde";
string p = "a*de";
cout << (isMatch(t, p) ? "Yes" : "No") ;
return 0;
}
Java
class GfG {
// n is the length of text t
// m is the length of patter p
static boolean isMatchRec(String t, String p, int n, int m) {
// empty pattern can only match with an empty string
if (m == 0)
return (n == 0);
// Empty string can match only with one or more occurrences of '*'
if (n == 0) {
for (int i = 0; i < m; i++)
if (p.charAt(i) != '*')
return false;
return true;
}
// Either the last characters match or the pattern has '?'
if (t.charAt(n - 1) == p.charAt(m - 1) || p.charAt(m - 1) == '?')
return isMatchRec(t, p, n - 1, m - 1);
// If last character is '*', two cases arise
// 1) We ignore it
// 2) We match it with a character
if (p.charAt(m - 1) == '*')
return isMatchRec(t, p, n, m - 1) || isMatchRec(t, p, n - 1, m);
return false;
}
// Wrapper over the above method
static boolean isMatch(String t, String p) {
return isMatchRec(t, p, t.length(), p.length());
}
public static void main(String[] args) {
String t = "abcde";
String p = "a*de";
System.out.println(isMatch(t, p) ? "Yes" : "No");
}
}
Python
# n is the length of text t
# m is the length of patter p
def isMatchRec(t, p, n, m):
# empty pattern can only match with an empty string
if m == 0:
return n == 0
# Empty string can match only with one or more occurrences of '*'
if n == 0:
return all(char == '*' for char in p[:m])
# Either the last characters match or the pattern has '?'
if t[n - 1] == p[m - 1] or p[m - 1] == '?':
return isMatchRec(t, p, n - 1, m - 1)
# If last character is '*', two cases arise
# 1) We ignore it
# 2) We match it with a character
if p[m - 1] == '*':
return isMatchRec(t, p, n, m - 1) or isMatchRec(t, p, n - 1, m)
return False
# Wrapper over the above method
def isMatch(t, p):
return isMatchRec(t, p, len(t), len(p))
t = "abcde"
p = "a*de"
print("Yes" if isMatch(t, p) else "No")
Using Dynamic Programming
We create a 2D dp array as twp parameters change in recursion and the size of the table is (m + 1) * (n + 1) as the range of parameters go from 0 to m and 0 to n.
dp[i][j] is true if prefix of length i of text t and prefix of length j of pattern p match
// both text and pattern are empty
dp[0][0] = true;
// pattern is empty
dp[i][0] = false;
// text is empty
dp[0][j] = p[0][j – 1] if p[j â 1] is ‘*’
f current characters match, result is same as result for lengths minus one. Characters match in two cases:
a) If pattern character is ‘?’ then it matches with any character of text.
b) If current characters in both match
if ( p[j â 1] == â?â || p[j â 1] == t[i – 1])
dp[i][j] = dp[i-1][j-1]
If we encounter â*â, two choices are possible cases
a) We ignore â*â character and move to next
b) ‘*’ character matches with ith character in text
if (pattern[j â 1] == â*â)
dp[i][j] = dp[i][j-1] || dp[i-1][j]
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isMatch(string t, string p)
{
int n = t.size();
int m = p.size();
// dp[i][j] will be true if t[0..i-1] matches p[0..j-1]
vector<vector<bool>> dp(n + 1, vector<bool>(m + 1, false));
// Empty pattern matches with empty string
dp[0][0] = true;
// Handle patterns with '*' at the beginning
for (int j = 1; j <= m; j++)
if (p[j - 1] == '*')
dp[0][j] = dp[0][j - 1];
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (p[j - 1] == t[i - 1] || p[j - 1] == '?')
{
// If the current characters match, or the pattern has a '?',
// inherit the result from the previous state.
dp[i][j] = dp[i - 1][j - 1];
}
else if (p[j - 1] == '*')
{
// If the current character in the pattern is '*', we either:
// 1. Ignore the '*' (dp[i][j-1]) or
// 2. Match '*' with one character from the string (dp[i-1][j]).
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
// The result is in dp[n][m]
return dp[n][m];
}
int main()
{
string t = "abcde";
string p = "a*de";
cout << (isMatch(t, p) ? "Yes" : "No") << endl;
return 0;
}
Java
import java.util.*;
class GfG {
public static boolean isMatch(String t, String p) {
int n = t.length();
int m = p.length();
// dp[i][j] will be true if t[0..i-1] matches p[0..j-1]
boolean[][] dp = new boolean[n + 1][m + 1];
// Empty pattern matches with empty string
dp[0][0] = true;
// Handle patterns with '*' at the beginning
for (int j = 1; j <= m; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// If the current characters match, or
// the pattern has a '?',
// inherit the result from the previous state.
if (p.charAt(j - 1) == t.charAt(i - 1) ||
p.charAt(j - 1) == '?') {
dp[i][j] = dp[i - 1][j - 1];
// If the current character in the pattern is '*', we either:
// 1. Ignore the '*' (dp[i][j-1]) or
// 2. Match '*' with one character from the string (dp[i-1][j])
} else if (p.charAt(j - 1) == '*') {.
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String t = "abcde";
String p = "a*de";
System.out.println(isMatch(t, p) ? "Yes" : "No");
}
}
Python
def is_match(t, p):
n = len(t)
m = len(p)
# dp[i][j] will be True if t[0..i-1] matches p[0..j-1]
dp = [[False] * (m + 1) for _ in range(n + 1)]
# Empty pattern matches with empty string
dp[0][0] = True
# Handle patterns with '*' at the beginning
for j in range(1, m + 1):
if p[j - 1] == '*':
dp[0][j] = dp[0][j - 1]
for i in range(1, n + 1):
for j in range(1, m + 1):
# If the current characters match, or the pattern has a '?',
# inherit the result from the previous state.
if p[j - 1] == t[i - 1] or p[j - 1] == '?':
dp[i][j] = dp[i - 1][j - 1]
# If the current character in the pattern is '*', we either:
# 1. Ignore the '*' (dp[i][j-1]) or
# 2. Match '*' with one character from the string (dp[i-1][j]).
elif p[j - 1] == '*':
dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
return dp[n][m]
# Example usage
t = "abcde"
p = "a*de"
print("Yes" if is_match(t, p) else "No")
Dry Run:
pattern = "a*b?d"str = "aabxd"
Initial Setup:
pattern.length() = 5str.length() = 5dp[6][6] matrix (since dp[str.length() + 1][pattern.length() + 1] is used).
Step 1: Initialize the DP matrix with 0.
- The entire matrix
dp[6][6] is initialized to 0.
Step 2: Set the first cell to true.
dp[0][0] = true because an empty pattern matches an empty string.
Step 3: Initialize the first row for '*'.
- Iterate through
pattern and mark cells dp[0][i] as true if the corresponding character in pattern is '*':- For
pattern[0] = 'a', dp[0][1] remains 0. - For
pattern[1] = '*', dp[0][2] = dp[0][1] = 0 (remains 0). - For
pattern[2] = 'b', dp[0][3] remains 0. - For
pattern[3] = '?', dp[0][4] remains 0. - For
pattern[4] = 'd', dp[0][5] remains 0.
Step 4: Initialize the first cell of the second row for '*'.
- This part of the code checks if the first character in
pattern is '*' and sets dp[0][1] = 1. However, in our case, the first character is 'a', so dp[0][1] remains 0.
Step 5: Fill the DP matrix row by row.
We fill the matrix based on the rules provided. Let’s go through each step:
Iteration 1: i = 1, str[0] = 'a'
j = 1 (pattern[0] = 'a'):- Match (
str[0] == pattern[0]), so dp[1][1] = dp[0][0] = 1.
j = 2 (pattern[1] = '*'):'*' can match empty, so dp[1][2] = dp[0][2] || dp[1][1] = 0 || 1 = 1.
j = 3 (pattern[2] = 'b'):- No match, so
dp[1][3] = 0.
j = 4 (pattern[3] = '?'):j = 5 (pattern[4] = 'd'):
Iteration 2: i = 2, str[1] = 'a'
j = 1 (pattern[0] = 'a'):- Match, so
dp[2][1] = dp[1][0] = 0.
j = 2 (pattern[1] = '*'):dp[2][2] = dp[1][2] || dp[2][1] = 1 || 0 = 1.
j = 3 (pattern[2] = 'b'):- No match, so
dp[2][3] = 0.
j = 4 (pattern[3] = '?'):- No match, so
dp[2][4] = 0.
j = 5 (pattern[4] = 'd'):- No match, so
dp[2][5] = 0.
Iteration 3: i = 3, str[2] = 'b'
j = 1 (pattern[0] = 'a'):- No match, so
dp[3][1] = 0.
j = 2 (pattern[1] = '*'):dp[3][2] = dp[2][2] || dp[3][1] = 1 || 0 = 1.
j = 3 (pattern[2] = 'b'):- Match, so
dp[3][3] = dp[2][2] = 1.
j = 4 (pattern[3] = '?'):- No match, so
dp[3][4] = 0.
j = 5 (pattern[4] = 'd'):- No match, so
dp[3][5] = 0.
Iteration 4: i = 4, str[3] = 'x'
j = 1 (pattern[0] = 'a'):- No match, so
dp[4][1] = 0.
j = 2 (pattern[1] = '*'):dp[4][2] = dp[3][2] || dp[4][1] = 1 || 0 = 1.
j = 3 (pattern[2] = 'b'):- No match, so
dp[4][3] = 0.
j = 4 (pattern[3] = '?'):- Match, so
dp[4][4] = dp[3][3] = 1.
j = 5 (pattern[4] = 'd'):- No match, so
dp[4][5] = 0.
Iteration 5: i = 5, str[4] = 'd'
j = 1 (pattern[0] = 'a'):- No match, so
dp[5][1] = 0.
j = 2 (pattern[1] = '*'):dp[5][2] = dp[4][2] || dp[5][1] = 1 || 0 = 1.
j = 3 (pattern[2] = 'b'):- No match, so
dp[5][3] = 0.
j = 4 (pattern[3] = '?'):- No match, so
dp[5][4] = 0.
j = 5 (pattern[4] = 'd'):- Match, so
dp[5][5] = dp[4][4] = 1.
Final Result:
- The value in the bottom-right cell,
dp[5][5], is 1, indicating that the pattern "a*b?d" matches the string "aabxd".
Time Complexity: O(n*m), As we are running a loop of size n*m, where n is the length of the string and m is the length of the pattern.
Space Complexity: O(n*m), As we have made a dp array of size n*m.
Space Optimized DP
If we take a closer look at the above solution, we can notice that we use only previous row entries, therefore we can optimize the space by storing only previous row.
C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isMatch(string t, string p)
{
int n = t.size();
int m = p.size();
// Create two 1D arrays for current and previous rows
vector<bool> prev(m + 1, false), curr(m + 1, false);
// Empty pattern matches with empty string
prev[0] = true;
// Handle patterns with '*' at the beginning
for (int j = 1; j <= m; j++)
if (p[j - 1] == '*')
prev[j] = prev[j - 1];
for (int i = 1; i <= n; i++)
{
// Empty pattern can't match non-empty string
curr[0] = false;
for (int j = 1; j <= m; j++)
{
// Characters match or '?' matches any character
if (p[j - 1] == t[i - 1] || p[j - 1] == '?')
curr[j] = prev[j - 1];
// '*' matches zero or more characters
else if (p[j - 1] == '*')
curr[j] = curr[j - 1] || prev[j];
else
curr[j] = false;
}
// Move to the next row
prev = curr;
}
return prev[m];
}
int main()
{
string t = "abcde";
string p = "a*de";
cout << (isMatch(t, p) ? "Yes" : "No") << endl;
return 0;
}
Java
import java.util.*;
class GfG {
public static boolean isMatch(String t, String p) {
int n = t.length();
int m = p.length();
// Create two 1D arrays for current and previous rows
boolean[] prev = new boolean[m + 1];
boolean[] curr = new boolean[m + 1];
// Empty pattern matches with empty string
prev[0] = true;
// Handle patterns with '*' at the beginning
for (int j = 1; j <= m; j++) {
if (p.charAt(j - 1) == '*') {
prev[j] = prev[j - 1];
}
}
for (int i = 1; i <= n; i++) {
// Empty pattern can't match non-empty string
curr[0] = false;
for (int j = 1; j <= m; j++) {
// Characters match or '?' matches any character
if (p.charAt(j - 1) == t.charAt(i - 1) ||
p.charAt(j - 1) == '?') {
curr[j] = prev[j - 1];
}
// '*' matches zero or more characters
else if (p.charAt(j - 1) == '*') {
curr[j] = curr[j - 1] || prev[j];
} else {
curr[j] = false;
}
}
// Copy the current row to the previous row
prev = curr.clone();
}
return prev[m];
}
public static void main(String[] args) {
String t = "abcde";
String p = "a*de";
System.out.println(isMatch(t, p) ? "Yes" : "No");
}
}
Python
def is_match(t, p):
n = len(t)
m = len(p)
# Create two 1D arrays for current and previous rows
prev = [False] * (m + 1)
curr = [False] * (m + 1)
# Empty pattern matches with empty string
prev[0] = True
# Handle patterns with '*' at the beginning
for j in range(1, m + 1):
if p[j - 1] == '*':
prev[j] = prev[j - 1]
for i in range(1, n + 1):
# Empty pattern can't match non-empty string
curr[0] = False
for j in range(1, m + 1):
# Characters match or '?' matches any character
if p[j - 1] == t[i - 1] or p[j - 1] == '?':
curr[j] = prev[j - 1]
# '*' matches zero or more characters
elif p[j - 1] == '*':
curr[j] = curr[j - 1] or prev[j]
else:
curr[j] = False
# Move to the next row
prev = curr[:]
return prev[m]
# Example usage
t = "abcde"
p = "a*de"
print("Yes" if is_match(t, p) else "No")
Time complexity: O(m x n).
Auxiliary space: O(m).
Simple Traversal Solution
At first, we initialize two pointers i and j to the beginning of the text and the pattern, respectively. We also initialize two variables startIndex and match to -1 and 0, respectively. startIndex will keep track of the position of the last ‘*’ character in the pattern, and match will keep track of the position in the text where the last proper match started.
We then loop through the text until we reach the end or find a character in the pattern that doesn’t match the corresponding character in the text. If the current characters match, we simply move to the next characters in both the pattern and the text. Ifnd if the pattern has a ‘?’ , we simply move to the next characters in both the pattern and the text. If the pattern has a ‘*’ character, then we mark the current position in the pattern and the text as a proper match by setting startIndex to the current position in the pattern and its match to the current position in the text. If there was no match and no ‘*’ character, then we understand we need to go through a different route henceforth, we backtrack to the last ‘*’ character position and try a different match by setting j to startIndex + 1, match to match + 1, and i to match.
Once we have looped over the text, we consume any remaining ‘*’ characters in the pattern, and if we have reached the end of both the pattern and the text, the pattern matches the text.
C++
#include <iostream>
using namespace std;
bool isMatch(string t, string p)
{
int n = t.length();
int m = p.length();
int i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (p[j] == '?' || p[j] == t[i])) {
i++;
j++;
}
else if (j < m && p[j] == '*') {
// Wildcard character '*', mark the current
// position in the pattern and the text as a
// proper match.
startIndex = j;
match = i;
j++;
}
else if (startIndex != -1) {
// No match, but a previous wildcard was found.
// Backtrack to the last '*' character position
// and try for a different match.
j = startIndex + 1;
match++;
i = match;
}
else {
// If none of the above cases comply, the
// pattern does not match.
return false;
}
}
// Consume any remaining '*' characters in the given
// pattern.
while (j < m && p[j] == '*') {
j++;
}
// If we have reached the end of both the pattern and
// the text, the pattern matches the text.
return j == m;
}
int main()
{
string t = "baaabab";
string p = "*****ba*****ab";
cout << (isMatch(t, p) ? "Yes" : "No");
}
Java
class GfG {
public static boolean isMatch(String t, String p) {
int n = t.length();
int m = p.length();
int i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (p.charAt(j) == '?' || p.charAt(j) == t.charAt(i))) {
i++;
j++;
} else if (j < m && p.charAt(j) == '*') {
// Wildcard character '*', mark the current
// position in the pattern and the text as a
// proper match.
startIndex = j;
match = i;
j++;
} else if (startIndex != -1) {
// No match, but a previous wildcard was found.
// Backtrack to the last '*' character position
// and try for a different match.
j = startIndex + 1;
match++;
i = match;
} else {
// If none of the above cases comply, the
// pattern does not match.
return false;
}
}
// Consume any remaining '*' characters in
// the given pattern.
while (j < m && p.charAt(j) == '*') {
j++;
}
// If we have reached the end of both the
// pattern and the text, the pattern matches
// the text.
return j == m;
}
public static void main(String[] args) {
String str = "baaabab";
String pattern = "*****ba*****ab";
System.out.println(isMatch(str, pattern) ? "Yes" : "No");
}
}
Python
def is_match(t: str, p: str) -> bool:
n = len(t)
m = len(p)
i = 0
j = 0
start_index = -1
match = 0
while i < n:
# Characters match or '?' in pattern matches any character.
if j < m and (p[j] == '?' or p[j] == t[i]):
i += 1
j += 1
elif j < m and p[j] == '*':
# Wildcard character '*', mark the current position in the
# pattern and the text as a proper match.
start_index = j
match = i
j += 1
elif start_index != -1:
# No match, but a previous wildcard was found.
# Backtrack to the last '*' character position and
# try for a different match.
j = start_index + 1
match += 1
i = match
else:
# If none of the above cases comply, the pattern does not match.
return False
# Consume any remaining '*' characters in the given pattern.
while j < m and p[j] == '*':
j += 1
return j == m
if __name__ == "__main__":
t = "baaabab"
p = "*****ba*****ab"
print("Yes" if is_match(t, p) else "No")
Time Complexity: O(n), where n is the length of the given text.
Auxiliary Space: O(1), because we only use constant amount of extra memory to store just the two pointers.
One more improvement is you can merge consecutive â*â in the pattern to single â*â as they mean the same thing. For example for pattern “*****ba*****abâ, if we merge consecutive stars, the resultant string will be “*ba*abâ. So, value of m is reduced from 14 to 6.
Please Login to comment...