Wildcard Pattern Matching: Given a string and a pattern containing wildcard characters, i.e., * and ?, where ? can match to any single character in the string and * can match to any number of characters including zero characters, design an efficient algorithm to check if the pattern matches with the complete string or not.

For example,

Input:  string = “xyxzzxy”, pattern = “x***y”
Output: Match
 
Input:  string = “xyxzzxy”, pattern = “x***x”
Output: No Match
 
Input:  string = “xyxzzxy”, pattern = “x***x?”
Output: Match
 
Input:  string = “xyxzzxy”, pattern = “*”
Output: Match

Practice this problem

The idea is to use dynamic programming to solve this problem. If we carefully analyze the problem, we can see that it can easily be further divided into subproblems. Let’s take the top-bottom approach to solve this problem.

For a given pattern[0…m] and word[0…n],

  • If pattern[m] == '*', if * matches the current character in the input string, move to the next character in the string; otherwise, ignore * and move to the next character in the pattern.
  • If pattern[m] == '?', ignore current characters of both string and pattern and check if pattern[0…m-1] matches word[0…n-1].
  • If the current character in the pattern is not a wildcard character, it should match the current character in the input string.

Special care has to be taken to handle base conditions:

  • If both the input string and pattern reach their end, return true.
  • If the only pattern reaches its end, return false.
  • If only the input string reaches its end, return true only if the remaining characters in the pattern are all *.

Following is the top-down DP solution in C++, Java, and Python using memoization:

C++


Download  Run Code

Output:

Match

Java


Download  Run Code

Output:

Match

Python


Download  Run Code

Output:

Match

The time complexity of the above top-down solution is O(m.n) and requires O(m.n) extra space, where n is the length of the text and m is the length of the pattern.

 
Following is an iterative C++, Java, and Python implementation of the above code:

C++


Download  Run Code

Output:

Match

Java


Download  Run Code

Output:

Match

Python


Download  Run Code

Output:

Match

The time complexity of the above bottom-up solution is O(m.n) and requires O(m.n) extra space, where n is the length of the text and m is the length of the pattern.