Wildcard Pattern Matching
Last Updated :
23 Jul, 2025
Given a text txt and a wildcard pattern pat, implement a wildcard pattern matching algorithm that finds if the wildcard pattern is matched with the text. The matching should cover the entire text. The wildcard pattern can include the characters '?' and '*' which denote:
- '?' - matches any single character
- '*' - Matches any sequence of characters (including the empty sequence)
Input: txt = "abcde", pat = "a?c*"
Output: true
Explanation: ? matches with b and * matches with "de".
Input: txt = "baaabab", pat = "a*ab"
Output: false
Explanation: Because in string pattern character 'a' at first position, pattern and text can't be matched.
Input: txt = "abc", pat = "*"
Output: true
Explanation: * matches with whole text "abc".
Using Recursion - O(2^(n+m)) Time and O(n) Space
We start matching the last characters of the both pattern and text. There are three possible cases:
Case 1: The character is ‘*’ . Here two cases arises as follows:
- We consider that '*' is equal to empty substring, and we move to the next character in pattern.
- We match '*' with one or more characters in Text. Here we move to next character in the text.
Case 2: The character is ‘?’ :
As '?' matches with any single character, we move to the next character in both pattern and text.
Case 3: The character in the pattern is not a wildcard:
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.
C++
// C++ program for wildcard pattern matching using
// recursion
#include <iostream>
#include <string>
using namespace std;
bool wildCardRec(string& txt, string& pat, int n, int m) {
// Empty pattern can match with a empty text only
if (m == 0)
return (n == 0);
// Empty text can match with a pattern consisting
// of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++)
if (pat[i] != '*')
return false;
return true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt[n - 1] == pat[m - 1] || pat[m - 1] == '?')
return wildCardRec(txt, pat, n - 1, m - 1);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat[m - 1] == '*')
return wildCardRec(txt, pat, n, m - 1) ||
wildCardRec(txt, pat, n - 1, m);
return false;
}
bool wildCard(string txt, string pat) {
int n = txt.size();
int m = pat.size();
return wildCardRec(txt, pat, n, m);
}
int main() {
string txt= "abcde";
string pat = "a*de";
cout << (wildCard(txt, pat) ? "true" : "false");
return 0;
}
Java
// Java program for wildcard pattern matching using recursion
class GfG {
static boolean wildCardRec(String txt,
String pat, int n, int m) {
// Empty pattern can match with an empty text only
if (m == 0)
return (n == 0);
// Empty text can match with a pattern consisting
// of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++)
if (pat.charAt(i) != '*')
return false;
return true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt.charAt(n - 1) == pat.charAt(m - 1) ||
pat.charAt(m - 1) == '?')
return wildCardRec(txt, pat, n - 1, m - 1);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat.charAt(m - 1) == '*')
return wildCardRec(txt, pat, n, m - 1) ||
wildCardRec(txt, pat, n - 1, m);
return false;
}
static boolean wildCard(String txt, String pat) {
int n = txt.length();
int m = pat.length();
return wildCardRec(txt, pat, n, m);
}
public static void main(String[] args) {
String txt = "abcde";
String pat = "a*de";
System.out.println(wildCard(txt, pat) ? "true" : "false");
}
}
Python
# Python program for wildcard pattern matching using
# recursion
def wildCardRec(txt, pat, n, m):
# Empty pattern can match with an empty text only
if m == 0:
return n == 0
# Empty text can match with a pattern consisting
# of '*' only.
if n == 0:
for i in range(m):
if pat[i] != '*':
return False
return True
# Either the characters match or pattern has '?'
# move to the next in both text and pattern
if txt[n - 1] == pat[m - 1] or pat[m - 1] == '?':
return wildCardRec(txt, pat, n - 1, m - 1)
# if the current character of pattern is '*'
# first case: It matches with zero character
# second case: It matches with one or more characters
if pat[m - 1] == '*':
return wildCardRec(txt, pat, n, m - 1) or \
wildCardRec(txt, pat, n - 1, m)
return False
def wildCard(txt, pat):
n = len(txt)
m = len(pat)
return wildCardRec(txt, pat, n, m)
if __name__ == "__main__":
txt = "abcde"
pat = "a*de"
print("true" if wildCard(txt, pat) else "false")
C#
// C# program for wildcard pattern
// matching using recursion
using System;
class GfG {
static bool wildCardRec(string txt,
string pat, int n, int m) {
// Empty pattern can match with an empty text only
if (m == 0)
return (n == 0);
// Empty text can match with a pattern consisting
// of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++)
if (pat[i] != '*')
return false;
return true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt[n - 1] == pat[m - 1] || pat[m - 1] == '?')
return wildCardRec(txt, pat, n - 1, m - 1);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat[m - 1] == '*')
return wildCardRec(txt, pat, n, m - 1) ||
wildCardRec(txt, pat, n - 1, m);
return false;
}
static bool wildCard(string txt, string pat) {
int n = txt.Length;
int m = pat.Length;
return wildCardRec(txt, pat, n, m);
}
static void Main(string[] args) {
string txt = "abcde";
string pat = "a*de";
Console.WriteLine(wildCard(txt, pat) ? "true" : "false");
}
}
JavaScript
// JavaScript program for wildcard pattern matching using
// recursion
function wildCardRec(txt, pat, n, m) {
// Empty pattern can match with an empty text only
if (m === 0)
return (n === 0);
// Empty text can match with a pattern consisting
// of '*' only.
if (n === 0) {
for (let i = 0; i < m; i++)
if (pat[i] !== '*')
return false;
return true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt[n - 1] === pat[m - 1] || pat[m - 1] === '?')
return wildCardRec(txt, pat, n - 1, m - 1);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat[m - 1] === '*')
return wildCardRec(txt, pat, n, m - 1) ||
wildCardRec(txt, pat, n - 1, m);
return false;
}
function wildCard(txt, pat) {
let n = txt.length;
let m = pat.length;
return wildCardRec(txt, pat, n, m);
}
let txt = "abcde";
let pat = "a*de";
console.log(wildCard(txt, pat) ? "true" : "false");
Using Memoization - O(n*m) Time and O(n*m) Space
In this problem, we can observe that the recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: The result of matching a pattern pat of length m with a text txt of length n, i.e., wildCardRec(txt, pat, n, m), depends on the optimal solutions of its subproblems. If the current characters of pat and txt match (or if the character in pat is a '?'), then the solution depends on wildCardRec(txt, pat, n-1, m-1). If the current character in pat is an *, the solution of the problem will depend on the optimal result of wildCardRec(txt, pat, n, m-1) and wildCardRec(txt, pat, n-1, m).
2. Overlapping Subproblems: When using a recursive approach for the wildcard matching problem, we notice that certain subproblems are solved multiple times. For example, when solving wildCardRec(txt, pat, n, m), we may repeatedly compute results for subproblems like wildCardRec(txt, pat, n-1, m-1) or wildCardRec(txt, pat, n, m-1) in different recursive paths.
- Since there are two parameters change in the recursive solution: the current indices of the text txt (ranging from 0 to n) and the pattern pat (ranging from 0 to m). Thus, we create a 2D array memo of size (n+1) by (m+1) for memoization.
- We initialize this array with -1 to indicate that no subproblem has been computed initially.
- We then modify our recursive solution to first check if memo[n][m] is -1; if it is, then only we proceed with further recursive calls.
C++
// C++ program for wildcard pattern
// matching using memoization
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool wildCardRec(string& txt, string& pat,
int n, int m, vector<vector<int>> &memo) {
// Empty pattern can match with a empty text only
if (m == 0)
return (n == 0);
// If result for this sub problem has been
// already computed, return it
if(memo[n][m] != -1)
return memo[n][m];
// Empty text can match with a pattern consisting
// of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++)
if (pat[i] != '*')
return memo[n][m] = false;
return memo[n][m] = true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt[n - 1] == pat[m - 1] || pat[m - 1] == '?')
return memo[n][m] =
wildCardRec(txt, pat, n - 1, m - 1, memo);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat[m - 1] == '*')
return memo[n][m] =
wildCardRec(txt, pat, n, m - 1, memo) ||
wildCardRec(txt, pat, n - 1, m, memo);
return memo[n][m] = false;
}
bool wildCard(string txt, string pat) {
int n = txt.size();
int m = pat.size();
vector<vector<int>> memo(n+1, vector<int>(m+1, -1));
return wildCardRec(txt, pat, n, m, memo);
}
int main() {
string txt= "abcde";
string pat = "a*de";
cout << (wildCard(txt, pat) ? "true" : "false");
return 0;
}
Java
// Java program for wildcard pattern matching
// using memoization
import java.util.Arrays;
class GfG {
static boolean wildCardRec(String txt,
String pat, int n, int m, int[][] memo) {
// Empty pattern can match with an empty text only
if (m == 0)
return (n == 0);
// If result for this subproblem has been
// already computed, return it
if (memo[n][m] != -1)
return memo[n][m] == 1;
// Empty text can match with a
// pattern consisting of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++) {
if (pat.charAt(i) != '*') {
memo[n][m] = 0;
return false;
}
}
memo[n][m] = 1;
return true;
}
// Either the characters match or pattern has '?'
// Move to the next in both text and pattern
if (txt.charAt(n - 1) == pat.charAt(m - 1) || pat.charAt(m - 1) == '?') {
memo[n][m] = wildCardRec(txt, pat, n - 1, m - 1, memo) ? 1 : 0;
return memo[n][m] == 1;
}
// If the current character of pattern is '*'
// First case: It matches with zero character
// Second case: It matches with one or more characters
if (pat.charAt(m - 1) == '*') {
memo[n][m] = (wildCardRec(txt, pat, n, m - 1, memo)
|| wildCardRec(txt, pat, n - 1, m, memo)) ? 1 : 0;
return memo[n][m] == 1;
}
memo[n][m] = 0;
return false;
}
static boolean wildCard(String txt, String pat) {
int n = txt.length();
int m = pat.length();
int[][] memo = new int[n + 1][m + 1];
for (int[] row : memo)
Arrays.fill(row, -1);
return wildCardRec(txt, pat, n, m, memo);
}
public static void main(String[] args) {
String txt = "abcde";
String pat = "a*de";
System.out.println(wildCard(txt, pat) ? "true" : "false");
}
}
Python
# Python program for wildcard pattern
# matching using memoization
def wildCardRec(txt, pat, n, m, memo):
# Empty pattern can match with an empty text only
if m == 0:
return n == 0
# If result for this subproblem has been
# already computed, return it
if memo[n][m] != -1:
return memo[n][m]
# Empty text can match with a pattern consisting
# of '*' only.
if n == 0:
for i in range(m):
if pat[i] != '*':
memo[n][m] = False
return False
memo[n][m] = True
return True
# Either the characters match or pattern has '?'
# move to the next in both text and pattern
if txt[n - 1] == pat[m - 1] or pat[m - 1] == '?':
memo[n][m] = wildCardRec(txt, pat, n - 1, m - 1, memo)
return memo[n][m]
# if the current character of pattern is '*'
# first case: It matches with zero character
# second case: It matches with one or more characters
if pat[m - 1] == '*':
memo[n][m] = wildCardRec(txt, pat, n, m - 1, memo) \
or wildCardRec(txt, pat, n - 1, m, memo)
return memo[n][m]
memo[n][m] = False
return False
def wildCard(txt, pat):
n = len(txt)
m = len(pat)
memo = [[-1 for _ in range(m + 1)] for _ in range(n + 1)]
return wildCardRec(txt, pat, n, m, memo)
if __name__ == "__main__":
txt = "abcde"
pat = "a*de"
print("true" if wildCard(txt, pat) else "false")
C#
// C# program for wildcard pattern matching
// using memoization
using System;
class GfG {
static bool WildCardRec(string txt, string pat,
int n, int m, int[,] memo) {
// Empty pattern can match with an empty
// text only
if (m == 0)
return (n == 0);
// If result for this subproblem has been
// already computed, return it
if (memo[n, m] != -1)
return memo[n, m] == 1;
// Empty text can match with a pattern
// consisting of '*' only.
if (n == 0) {
for (int i = 0; i < m; i++) {
if (pat[i] != '*') {
memo[n, m] = 0;
return false;
}
}
memo[n, m] = 1;
return true;
}
// Either the characters match or pattern has '?'
// Move to the next in both text and pattern
if (txt[n - 1] == pat[m - 1] || pat[m - 1] == '?') {
memo[n, m] = WildCardRec(txt, pat, n - 1, m - 1, memo) ? 1 : 0;
return memo[n, m] == 1;
}
// If the current character of pattern is '*'
// First case: It matches with zero character
// Second case: It matches with one or more characters
if (pat[m - 1] == '*') {
memo[n, m] = (WildCardRec(txt, pat, n, m - 1, memo)
|| WildCardRec(txt, pat, n - 1, m, memo)) ? 1 : 0;
return memo[n, m] == 1;
}
memo[n, m] = 0;
return false;
}
static bool WildCard(string txt, string pat) {
int n = txt.Length;
int m = pat.Length;
int[,] memo = new int[n + 1, m + 1];
// Initialize memo array with -1
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++)
memo[i, j] = -1;
}
return WildCardRec(txt, pat, n, m, memo);
}
static void Main(string[] args) {
string txt = "abcde";
string pat = "a*de";
Console.WriteLine(WildCard(txt, pat) ? "true" : "false");
}
}
JavaScript
// JavaScript program for wildcard pattern
// matching using memoization
function wildCardRec(txt, pat, n, m, memo) {
// Empty pattern can match with an empty text only
if (m === 0)
return n === 0;
// If result for this subproblem has been
// already computed, return it
if (memo[n][m] !== -1)
return memo[n][m];
// Empty text can match with a pattern consisting
// of '*' only.
if (n === 0) {
for (let i = 0; i < m; i++)
if (pat[i] !== '*')
return memo[n][m] = false;
return memo[n][m] = true;
}
// Either the characters match or pattern has '?'
// move to the next in both text and pattern
if (txt[n - 1] === pat[m - 1] || pat[m - 1] === '?')
return memo[n][m] = wildCardRec(txt, pat, n - 1, m - 1, memo);
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more characters
if (pat[m - 1] === '*')
return memo[n][m] = wildCardRec(txt, pat, n, m - 1, memo)
|| wildCardRec(txt, pat, n - 1, m, memo);
return memo[n][m] = false;
}
function wildCard(txt, pat) {
let n = txt.length;
let m = pat.length;
let memo = Array.from(Array(n + 1), () => Array(m + 1).fill(-1));
return wildCardRec(txt, pat, n, m, memo);
}
const txt = "abcde";
const pat = "a*de";
console.log(wildCard(txt, pat) ? "true" : "false");
Using Bottom-Up DP (Tabulation) - O(n*m) Time and O(n*m) Space
The approach is similar to the previous one; however, instead of solving the problem recursively, we iteratively build the solution using a bottom-up manner. We maintain a dp[][] table such that dp[i][j] stores whether the pattern pat[0...j-1] matches with the text txt[0...i-1].
C++
// C++ program for wild card matching
// using tabulation
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool wildCard(string& txt, string& pat) {
int n = txt.size();
int m = pat.size();
// dp[i][j] will be true if txt[0..i-1] matches pat[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 (pat[j - 1] == '*')
dp[0][j] = dp[0][j - 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (pat[j - 1] == txt[i - 1] || pat[j - 1] == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
dp[i][j] = dp[i - 1][j - 1];
}
else if (pat[j - 1] == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[n][m];
}
int main() {
string txt = "abcde";
string pat = "a*de";
cout << (wildCard(txt, pat) ? "true" : "false") << endl;
return 0;
}
Java
// Java program for wild card matching using tabulation
import java.util.Arrays;
class GfG {
static boolean wildCard(String txt, String pat) {
int n = txt.length();
int m = pat.length();
// dp[i][j] will be true if txt[0..i-1] matches pat[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 (pat.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 (pat.charAt(j - 1) == txt.charAt(i - 1)
|| pat.charAt(j - 1) == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
dp[i][j] = dp[i - 1][j - 1];
}
else if (pat.charAt(j - 1) == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String txt = "abcde";
String pat = "a*de";
System.out.println(wildCard(txt, pat) ? "true" : "false");
}
}
Python
# Python program for wild card matching using tabulation
def wildCard(txt, pat):
n = len(txt)
m = len(pat)
# dp[i][j] will be True if txt[0..i-1] matches pat[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 pat[j - 1] == '*':
dp[0][j] = dp[0][j - 1]
for i in range(1, n + 1):
for j in range(1, m + 1):
if pat[j - 1] == txt[i - 1] or pat[j - 1] == '?':
# Either the characters match or pattern has '?'
# result will be same as previous state
dp[i][j] = dp[i - 1][j - 1]
elif pat[j - 1] == '*':
# if the current character of pattern is '*'
# first case: It matches with zero character
# second case: It matches with one or more
dp[i][j] = dp[i][j - 1] or dp[i - 1][j]
return dp[n][m]
if __name__ == "__main__":
txt = "abcde"
pat = "a*de"
print("true" if wildCard(txt, pat) else "false")
C#
// C# program for wild card matching using tabulation
using System;
class GfG {
static bool WildCard(string txt, string pat) {
int n = txt.Length;
int m = pat.Length;
// dp[i, j] will be true if txt[0..i-1] matches pat[0..j-1]
bool[,] dp = new bool[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 (pat[j - 1] == '*')
dp[0, j] = dp[0, j - 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (pat[j - 1] == txt[i - 1] || pat[j - 1] == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
dp[i, j] = dp[i - 1, j - 1];
}
else if (pat[j - 1] == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
dp[i, j] = dp[i, j - 1] || dp[i - 1, j];
}
}
}
return dp[n, m];
}
static void Main(string[] args) {
string txt = "abcde";
string pat = "a*de";
Console.WriteLine(WildCard(txt, pat) ? "true" : "false");
}
}
JavaScript
// JavaScript program for wild card matching using tabulation
function wildCard(txt, pat) {
const n = txt.length;
const m = pat.length;
// dp[i][j] will be true if txt[0..i-1] matches pat[0..j-1]
const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(false));
// Empty pattern matches with empty string
dp[0][0] = true;
// Handle patterns with '*' at the beginning
for (let j = 1; j <= m; j++)
if (pat[j - 1] === '*')
dp[0][j] = dp[0][j - 1];
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (pat[j - 1] === txt[i - 1] || pat[j - 1] === '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
dp[i][j] = dp[i - 1][j - 1];
}
else if (pat[j - 1] === '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[n][m];
}
const txt = "abcde";
const pat = "a*de";
console.log(wildCard(txt, pat) ? "true" : "false");
Using Space Optimized DP - O(n*m) Time and O(m) Space
If we take a closer look at the above solution, we can notice that we use only row entries, previous and current one. Therefore we can optimize the space by storing only rows.
C++
// C++ program for wild card matching using
// space optimized dp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool wildCard(string txt, string pat) {
int n = txt.size();
int m = pat.size();
vector<bool> prev(m+1, false);
vector<bool> 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 (pat[j - 1] == '*')
prev[j] = prev[j-1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (pat[j - 1] == txt[i - 1] || pat[j - 1] == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
curr[j] = prev[j - 1];
}
else if (pat[j - 1] == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
curr[j] = curr[j - 1] || prev[j];
}
}
prev = curr;
}
return prev[m];
}
int main() {
string txt = "abcde";
string pat = "a*de";
cout << (wildCard(txt, pat) ? "true" : "false") << endl;
return 0;
}
Java
// Java program for wild card matching using space optimized
// dp
class GfG {
static boolean wildCard(String txt, String pat) {
int n = txt.length();
int m = pat.length();
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 (pat.charAt(j - 1) == '*')
prev[j] = prev[j - 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (pat.charAt(j - 1) == txt.charAt(i - 1)
|| pat.charAt(j - 1) == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
curr[j] = prev[j - 1];
}
else if (pat.charAt(j - 1) == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
curr[j] = curr[j - 1] || prev[j];
} else {
curr[j] = false;
}
}
// Copy current row to previous row
System.arraycopy(curr, 0, prev, 0, m + 1);
}
return prev[m];
}
public static void main(String[] args) {
String txt = "abcde";
String pat = "a*de";
System.out.println(wildCard(txt, pat) ? "true" : "false");
}
}
Python
# Python program for wild card matching using space optimized
# DP
def wildCard(txt, pat):
n = len(txt)
m = len(pat)
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 pat[j - 1] == '*':
prev[j] = prev[j - 1]
for i in range(1, n + 1):
for j in range(1, m + 1):
if pat[j - 1] == txt[i - 1] or pat[j - 1] == '?':
# Either the characters match or pattern has '?'
# result will be same as previous state
curr[j] = prev[j - 1]
elif pat[j - 1] == '*':
# if the current character of pattern is '*'
# first case: It matches with zero character
# second case: It matches with one or more
curr[j] = curr[j - 1] or prev[j]
else:
curr[j] = False
# Copy current row to previous row
prev = curr[:]
return prev[m]
txt = "abcde"
pat = "a*de"
print("true" if wildCard(txt, pat) else "false")
C#
// C# program for wild card matching using Space optimized DP
using System;
class GfG {
static bool WildCard(string txt, string pat) {
int n = txt.Length;
int m = pat.Length;
bool[] prev = new bool[m + 1];
bool[] curr = new bool[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 (pat[j - 1] == '*')
prev[j] = prev[j - 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (pat[j - 1] == txt[i - 1] || pat[j - 1] == '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
curr[j] = prev[j - 1];
}
else if (pat[j - 1] == '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
curr[j] = curr[j - 1] || prev[j];
} else {
curr[j] = false;
}
}
// Copy current row to previous row
Array.Copy(curr, prev, m + 1);
}
return prev[m];
}
static void Main(string[] args) {
string txt = "abcde";
string pat = "a*de";
Console.WriteLine(WildCard(txt, pat) ? "true" : "false");
}
}
JavaScript
// JavaScript program for wild card matching using space optimized
// DP
function wildCard(txt, pat) {
const n = txt.length;
const m = pat.length;
let prev = new Array(m + 1).fill(false);
let curr = new Array(m + 1).fill(false);
// Empty pattern matches with empty string
prev[0] = true;
// Handle patterns with '*' at the beginning
for (let j = 1; j <= m; j++) {
if (pat[j - 1] === '*')
prev[j] = prev[j - 1];
}
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (pat[j - 1] === txt[i - 1] || pat[j - 1] === '?') {
// Either the characters match or pattern has '?'
// result will be same as previous state
curr[j] = prev[j - 1];
}
else if (pat[j - 1] === '*') {
// if the current character of pattern is '*'
// first case: It matches with zero character
// second case: It matches with one or more
curr[j] = curr[j - 1] || prev[j];
} else {
curr[j] = false;
}
}
// Copy current row to previous row
prev = [...curr];
}
return prev[m];
}
const txt = "abcde";
const pat = "a*de";
console.log(wildCard(txt, pat) ? "true" : "false");
Simple Traversal Solution - O(n) Time and O(1) Space
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++
// C++ program for wild card matching using single
// traversal
#include <iostream>
using namespace std;
bool wildCard(string txt, string pat) {
int n = txt.length();
int m = pat.length();
int i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (pat[j] == '?' || pat[j] == txt[i])) {
i++;
j++;
}
else if (j < m && pat[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 && pat[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 txt = "baaabab";
string pat = "*****ba*****ab";
cout << (wildCard(txt, pat) ? "true" : "false");
}
Java
// Java program for wild card matching using single
// traversal
class GfG {
static boolean wildCard(String txt, String pat) {
int n = txt.length();
int m = pat.length();
int i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (pat.charAt(j) == '?'
|| pat.charAt(j) == txt.charAt(i))) {
i++;
j++;
}
else if (j < m && pat.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 && pat.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 txt = "baaabab";
String pat = "*****ba*****ab";
System.out.println(wildCard(txt, pat) ? "true" : "false");
}
}
Python
# Python program for wild card matching using single
# traversal
def wildCard(txt, pat):
n = len(txt)
m = len(pat)
i = 0
j = 0
startIndex = -1
match = 0
while i < n:
# Characters match or '?' in pattern matches
# any character.
if j < m and (pat[j] == '?' or pat[j] == txt[i]):
i += 1
j += 1
elif j < m and pat[j] == '*':
# Wildcard character '*', mark the current
# position in the pattern and the text as a
# proper match.
startIndex = j
match = i
j += 1
elif 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 += 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 pat[j] == '*':
j += 1
# If we have reached the end of both the pattern and
# the text, the pattern matches the text.
return j == m
if __name__ == "__main__":
txt = "baaabab"
pat = "*****ba*****ab"
print("true" if wildCard(txt, pat) else "false")
C#
// C# program for wild card matching using single
// traversal
using System;
class GfG {
static bool WildCard(string txt, string pat) {
int n = txt.Length;
int m = pat.Length;
int i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (pat[j] == '?' || pat[j] == txt[i])) {
i++;
j++;
}
else if (j < m && pat[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 && pat[j] == '*') {
j++;
}
// If we have reached the end of both the pattern and
// the text, the pattern matches the text.
return j == m;
}
static void Main(string[] args) {
string txt = "baaabab";
string pat = "*****ba*****ab";
Console.WriteLine(WildCard(txt, pat) ? "true" : "false");
}
}
JavaScript
// JavaScript program for wild card matching using single
// traversal
function wildCard(txt, pat) {
let n = txt.length;
let m = pat.length;
let i = 0, j = 0, startIndex = -1, match = 0;
while (i < n) {
// Characters match or '?' in pattern matches
// any character.
if (j < m && (pat[j] === '?' || pat[j] === txt[i])) {
i++;
j++;
}
else if (j < m && pat[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 && pat[j] === '*') {
j++;
}
// If we have reached the end of both the pattern and
// the text, the pattern matches the text.
return j === m;
}
let txt = "baaabab";
let pat = "*****ba*****ab";
console.log(wildCard(txt, pat) ? "true" : "false");
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem