Wildcard Pattern Matching | Practice | GeeksforGeeks

Given two strings 'str' and a wildcard pattern 'pattern' of length N and M respectively,  You have to print '1' if the wildcard pattern is matched with str else print '0' .

The wildcard pattern can include the characters ‘?’ and ‘*’
‘?’ – matches any single character
‘*’ – Matches any sequence of characters (including the empty sequence)
Note: The matching should cover the entire str (not partial str).
 
Example 1:
Input:
pattern = "ba*a?"
str = "baaabab"
Output: 1
Explanation: replace '*' with "aab" and 
'?' with 'b'. 

Example 2:
Input:
pattern = "a*ab"
str = "baaabab"
Output: 0
Explanation: Because of'a' at first position,
pattern and str can't be matched. 


Your Task:
You don't need to read input or print anything. Your task is to complete the function wildCard() which takes the two strings 'pattern' and 'str' as input parameters and returns the answer.
 
Expected Time Complexity: O(N*M)
Expected Auxiliary Space: O(N*M)

Constraints:
1 <= length of(str,pat) <= 200
0
rounakdiptaghosh19996 days ago
bool solve(string s, string p) {       int m = s.size();       int n = p.size();              bool dp[m+1][n+1];       dp[0][0]=true;       for(int i=1;i<=m;i++) dp[i][0]=false;       for(int i=1;i<=n;i++){           if(p[i-1]=='*')               dp[0][i]=dp[0][i-1];           else              dp[0][i]=false;       }              for(int i=1;i<m+1;i++){           for(int j=1;j<n+1;j++){               if(s[i-1]==p[j-1] || p[j-1]=='?') dp[i][j]=dp[i-1][j-1];               else if(p[j-1]=='*') dp[i][j]=dp[i-1][j]||dp[i][j-1];               else dp[i][j]=false;           }       }       return dp[m][n];   }
   int wildCard(string pattern,string str)   {       if(solve(str,pattern)==true) return 1;       else return 0;   }
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(N*M) and space complexity as O(N*M) is as follows :- 
 
Execution Time :- 0.06 / 1.04 sec
 
int dp[201][201];      int helper(string pattern,int ind1,string str,int ind2){       if(ind2 == str.length()){           while(ind1 < pattern.length() && pattern[ind1] == '*') ind1++;           if(ind1 == pattern.length()) return (1);           return (0);       }       if(ind1 == pattern.length()){           if(ind2 == str.length()) return (1);           return (0);       }              if(dp[ind1][ind2] != -1) return (dp[ind1][ind2]);              if(pattern[ind1] == '*'){           if(helper(pattern,ind1+1,str,ind2)) return (dp[ind1][ind2] = 1);           for(int i = ind2; i < str.length(); i++){               if(helper(pattern,ind1,str,i+1)) return (dp[ind1][ind2] = 1);           }       }       else if(pattern[ind1] == '?'){           if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1);       }       else{           if(pattern[ind1] != str[ind2]) return (dp[ind1][ind2] = 0);           else{               if(helper(pattern,ind1+1,str,ind2+1)) return (dp[ind1][ind2] = 1);           }       }              return (dp[ind1][ind2] = 0);   }      int wildCard(string pattern,string str){       memset(dp,-1,sizeof dp);       return helper(pattern,0,str,0);   }
0
swarajpawar3 weeks ago
class Solution{ public:/*You are required to complete this method*/   int f(int i,int j,string &p, string &s,vector<vector<int>>&dp){       if(i<0 and j<0)return true;       if(i<0 and j>=0)return false;       if(j<0 and i>=0){           for(int k=0;k<=i;k++){               if(p[k]!='*')return false;           }           return true;       }       if(dp[i][j]!=-1)return dp[i][j];       if(p[i]==s[j] or p[i]=='?')return dp[i][j]=f(i-1,j-1,p,s,dp);       if(p[i]=='*'){           return dp[i][j]=(f(i-1,j,p,s,dp) | f(i,j-1,p,s,dp));       }       return dp[i][j]=false;   }   int wildCard(string pattern,string str)   {       int n=pattern.size();       int m=str.size();       vector<vector<int>>dp(n,vector<int>(m,-1));       return f(n-1,m-1,pattern,str,dp);   }};
0
18pa1a04771 month ago
top down dp
class Solution:
    def wildCard(self,s1,s2):
        def m(s1,s2,i,j,dp):
            for n in range(i,len(s1)):
                 if s1[n]=="*":
                       i=n
                 else:
                        break
            if i==len(s1) and  j==len(s2):
                return True
            if i==len(s1)-1 and s1[i]=="*" :
                return True
            if (i==len(s1) or j==len(s2)):
                return False
            if dp[i][j]!=-1:
                      return dp[i][j]
            if s1[i]==s2[j] or s1[i]=="?":
                   val=m(s1,s2,i+1,j+1,dp)
                   dp[i][j]=val
                   return dp[i][j]
            else:
                    if s1[i]!=s2[j] and s1[i]!="*":
                                 return False
                    else:
                            for n in range(i,len(s1)):
                                    if s1[n]=="*":
                                             i=n
                                    else:
                                             i=n
                                             break
                            if i==len(s1):
                                   return  True
                            val=m(s1,s2,i,j,dp)
                            for k in range(j+1,len(s2)):
                                        val=val or m(s1,s2,i,k,dp)
                            
                            dp[i][j]=val
                            return dp[i][j]
        dp=[]
        l=max(len(s1),len(s2))
        for i in range(l+1):
                dp.append([])
                for j in range(l+1):
                    dp[i].append(-1)
        if m(s1,s2,0,0,dp):
            return 1
        else:
            return 0
 python solution for this
0
sandeep55211 month ago
1-D Array Space Optimized Tabulation (Time Taken 0.0)
int wildCard(string a,string b)
   {
       int m=a.size(),n=b.size();
       vector<bool> f(n+1,false),s(n+1);
       f[0]=true;
       for(int i=1;i<=m;i++){
           for(int j=0;j<=n;j++){
               if(!j){
                   if(a[i-1] =='*' and f[0]) s[0]=true;
                   else s[0]=false;
                   continue;
               }
               if(a[i-1]==b[j-1] or a[i-1]=='?') s[j]=f[j-1];
               else if(a[i-1]=='*') s[j]= f[j] or s[j-1];
               else s[j]=false;
           }
           f=s;
       }
       return f[n];
   }
+1
madhukartemba1 month ago
4 JAVA SOLUTIONS:
SOURCE: https://www.youtube.com/watch?v=ZmlQ3vgAOMo
RECURSION:
class Solution
{
    
    private boolean rec(int i, int j, StringBuilder str1, StringBuilder str2)
    {
        if(i<0 && j>=0) return false;
        else if(i<0 && j<0) return true;
        else if(i>=0 && j<0)
        {
            while(i>=0)
            {
                if(str1.charAt(i)!='*') return false;
                i--;
            }
            return true;
        }
        
        if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')
        {
            return rec(i-1, j-1, str1, str2);
        }
        
        if(str1.charAt(i)=='*')
        {
            return rec(i-1, j, str1, str2) || rec(i, j-1, str1, str2);
        }
        
        return false;
        
        
    }
    
    
    
    int wildCard(String pattern, String str)
    {
        StringBuilder str1 = new StringBuilder(pattern);
        StringBuilder str2 = new StringBuilder(str);
        
        
        return rec(str1.length()-1, str2.length()-1, str1, str2) ? 1 : 0;
        
        
    }
}
 
RECURSION WITH MEMOIZATION:
class Solution
{
    
    private int rec(int i, int j, StringBuilder str1, StringBuilder str2, int dp[][])
    {
        if(i<0 && j>=0) return 0;
        else if(i<0 && j<0) return 1;
        else if(i>=0 && j<0)
        {
            while(i>=0)
            {
                if(str1.charAt(i)!='*') return 0;
                i--;
            }
            return 1;
        }
        
        
        if(dp[i][j] != -1) return dp[i][j];
        
        if(str1.charAt(i)==str2.charAt(j) || str1.charAt(i)=='?')
        {
            return dp[i][j] = rec(i-1, j-1, str1, str2, dp);
        }
        
        if(str1.charAt(i)=='*')
        {
            return dp[i][j] = (rec(i-1, j, str1, str2, dp)==1 || rec(i, j-1, str1, str2, dp)==1) ? 1 : 0;
        }
        
        return dp[i][j] = 0;
        
        
    }
    
    
    
    int wildCard(String pattern, String str)
    {
        StringBuilder str1 = new StringBuilder(pattern);
        StringBuilder str2 = new StringBuilder(str);
        
        int n = str1.length();
        int m = str2.length();
        
        int dp[][] = new int[n][m];
        
        for(int i=0; i<n; i++)
        {
            Arrays.fill(dp[i], -1);
        }
        
        return rec(n-1, m-1, str1, str2, dp);
        
        
    }
}
 
2D ARRAY DYNAMIC PROGRAMMING:
class Solution
{
    int wildCard(String pattern, String str)
    {
        StringBuilder str1 = new StringBuilder(pattern);
        StringBuilder str2 = new StringBuilder(str);
        
        int n = str1.length();
        int m = str2.length();
        
        
        boolean dp[][] = new boolean[n+1][m+1];
        
        
        for(int i=0; i<=n; i++)
        {
            boolean flag = true;
            for(int x=1; x<=i; x++)
            {
                if(str1.charAt(x-1)!='*')
                {
                    flag = false;
                    break;
                }
            }
            
            dp[i][0] = flag;
            
        }
        
        
        for(int j=1; j<=m; j++)
        {
            dp[0][j] = false;
        }
        
        
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=m; j++)
            {
                if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')
                {
                    dp[i][j] = dp[i-1][j-1];
                }
                else if (str1.charAt(i-1)=='*')
                {
                    dp[i][j] = dp[i-1][j] || dp[i][j-1];
                }
                else
                {
                    dp[i][j] = false;
                }
            }
        }
        
        return dp[n][m] ? 1 : 0;
        
    }
}
 
1D ARRAY DYNAMIC PROGRAMMING:
 
class Solution
{
    int wildCard(String pattern, String str)
    {
        StringBuilder str1 = new StringBuilder(pattern);
        StringBuilder str2 = new StringBuilder(str);
        
        int n = str1.length();
        int m = str2.length();
        
        boolean prev[] = new boolean[m+1], cur[] = new boolean[m+1];
        
        prev[0] = true;
        
        for(int j=1; j<=m; j++)
        {
            prev[j] = false;
        }
        
        
        for(int i=1; i<=n; i++)
        {
            boolean flag = true;
            for(int x=1; x<=i; x++)
            {
                if(str1.charAt(x-1)!='*')
                {
                    flag = false;
                    break;
                }
            }
            
            cur[0] = flag;
            
            
            for(int j=1; j<=m; j++)
            {
                if(str1.charAt(i-1)==str2.charAt(j-1) || str1.charAt(i-1)=='?')
                {
                    cur[j] = prev[j-1];
                }
                else if (str1.charAt(i-1)=='*')
                {
                    cur[j] = prev[j] || cur[j-1];
                }
                else
                {
                    cur[j] = false;
                }
                
            }
            
            //Copy cur into prev for next iteration
            for(int k=0; k<=m; k++)
            {
                prev[k] = cur[k];
            }
            
        }
        
        return cur[m] ? 1 : 0;
        
    }
}
0
tirtha19025682 months ago
class Solution
{
   int wildCard(String pattern, String str)
   {
       boolean[][]dp = new boolean[pattern.length()+1][str.length()+1];
       dp[0][0] = true;
       
       for(int i=0;i<dp.length;i++){
           for(int j=0;j<dp[0].length;j++){
               if(i==0 && j==0) dp[i][j] = true;
               else if(i==0) dp[i][j] = false;
               else if(j==0) {
                   if(pattern.charAt(i-1) == '*'){
                       dp[i][j] = dp[i-1][j];
                   }else{
                       dp[i][j] = false;
                   }
                   
               }
           }
           
       }
       
       for(int i=1;i<dp.length;i++){
           for(int j=1;j<dp[0].length;j++){
              if(pattern.charAt(i-1) == '?' || pattern.charAt(i-1) == str.charAt(j-1)){
                 dp[i][j] = dp[i-1][j-1];
             }
             else if(pattern.charAt(i-1) == '*'){
                 dp[i][j] = dp[i][j-1] || dp[i-1][j];
             }
             else dp[i][j] = false;
           }
       }
       
       if(dp[pattern.length()][str.length()] == true ) return 1;
       return 0;
   }
}

+1
equbalzeeshan3 months ago
O(N) time and O(1) space solution
Explanation: For each element in s: 1. If *s==*p or *p == ‘?’ which means this is a match, then go to next element s++ p++. 2. If *p=='*', this is also a match, but one or many chars may be available, so save this *'s position and the matched s position. 3. If not match, then we check if there is a * that previously showed up,        → if there is no *,  return false;        → if there is an *,  we set current p to the next element of *, and set current s to the next saved s position.
	int wildCard(string pat,string str) {
        int S = str.length(), P = pat.length(), star_p = -1, star_s;
        int s = 0, p = 0;
        
        while(s < S) {
            if(p < P && (str[s] == pat[p] || pat[p] == '?')) {
                s++;
                p++;
            }
            else if(p < P && pat[p] == '*') {
                star_p = p;
                star_s = s; // Dont increment s '*' can match '' too
                p++;
            }
            else if(star_p != -1) {
                p = star_p + 1;
                s = star_s;
                star_s++;
            }
            else
                return false;
        }
        
        while(p < P && pat[p] == '*') p++;
        return p == P;
    }
0
bhaskarmaheshwari83 months ago
int help(string pat,string str,int n1,int n2)   {       if(n1==0&&n2==0)       return 1;              if(n1==0)       return 0;              if(n2==0)       {           for(int i=0;i<n1;i++)           {               if(pat[i]!='*')               return 0;           }           return 1;       }              if(pat[n1-1]==str[n2-1]||pat[n1-1]=='?')       return help(pat,str,n1-1,n2-1);       else if(pat[n1-1]=='*')       {           return help(pat,str,n1-1,n2)||help(pat,str,n1,n2-1);       }       else        {           return 0;       }          }      int wildCard(string pattern,string str)   {              int n1=pattern.size();       int n2=str.size();              return help(pattern,str,n1,n2);   }
0
choudharymanojloul8444 months ago
 int solve(string patt,string str,int i,int j,int pl,int sl)
    {
        if(i==pl && j==sl)
            return 1;
        
        if(j==sl)
        {
            while(i!=pl)
            {
                if(patt[i]!='*')
                 return 0;
                 
                 i++;
            }
            return 1;
        }
        
        if(i==pl)
         return 0;
        
        if(t[i][j]!=-1)
         return t[i][j];
         
        if(patt[i]=='*')
        {
            return t[i][j]=solve(patt,str,i+1,j,pl,sl)||solve(patt,str,i,j+1,pl,sl);
                
        }
        
        if(patt[i]=='?')
        {
            return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);
        }
        
        if(patt[i]!=str[j])
            return t[i][j]=0;
                
        return t[i][j]=solve(patt,str,i+1,j+1,pl,sl);
    }
    int wildCard(string pattern,string str)
    {
       for(int i=0;i<pattern.size();++i)
       {
           for(int j=0;j<str.size();++j)
           t[i][j]=-1;
       }
        return solve(pattern,str,0,0,pattern.size(),str.size());
        
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.