# Wild card matching problem using Dynamic programming (DP)

Here, we are going to solve the **wild chard matching problem using dynamic programming (DP) using C++ program**.

Submitted by Ritik Aggarwal, on December 14, 2018

## Problem statement

You are given two strings (one query and other pattern). You have to find whether the pattern matches to query or not. Print '1' if matches otherwise '0'. Some rules for matching:

- A
**"*"**can match any substring (blank spaces also). - A
**"?"**can match any single character (excluding blank spaces).

**Constraints:** (length of pattern) * (length of query) < 100000000

SAMPLE INPUT - 1: absbsbs a*?bs SAMPLE OUTPUT -1 : 1 SAMPLE INPUT – 2: avdgdv a?g* SAMPLE OUTPUT – 2: 0

## Explanation

**For the sample Input1,**

'*' can be replaced with 'bsb' and '?' can be replaced with 's'. Thus, both pattern and query matches so the output is 1.

**For the sample input2,**

'*' can be replaced with 'dv' but we cannot replace '?' with 'vd' as it can replace only one character. Thus, pattern and query cannot match so the output is 0.

## Algorithm

- STEP-1: Create a 2D dp matrix where j
^{th}cell of i^{th}row represent whether the pattern (from i^{th}index to the end) and the query (from j^{th}index to end) matches or not. - STEP-2: If pattern is the empty and the query is non-empty then it does not matches. So initializing dp matrix with false for the cell corresponding to this situation.
- STEP-3: if the query is empty and the pattern contains all '*' (pattern is something like ******) then put these corresponding values true.
- STEP-4: Start filling the dp matrix from right to left and bottom to top.
- STEP-5: If the ith character of pattern matches with jth character of query or the ith character is '?' then we can simply remove that ith character from pattern and jth character from query and check the right-bottom box and put its value in our current cell.
- STEP-6: if ith character of the pattern is '*' then check the right adjacent box(this box corresponds to situation when we remove the jth character from query) , bottom box(this box corresponds to situation when we remove the ith character from pattern) and the right-bottom adjacent(this box corresponds to situation when we remove the jth character from query and remove ith character from the pattern) value. If any of them is true then put true in current cell.
- STEP-7: Otherwise, set cells to false
- STEP-8: return the answer of i=0 and j=0 as they represent full query and pattern.

**The time complexity of the above code is O(length of pattern * length of query).**

## C++ program for wild card matching problem using Dynamic programming

#include <iostream> using namespace std; bool wildCard(string pattern, string s){ bool dp[pattern.length() + 1][s.length() + 1] = {false}; // Intialization of few values necessary for the dp relations // Case 1. pattern is a blank string // In this case we only have to initialize right-bottom // corner value to true as pattern is also empty and s is also empty dp[pattern.length()][s.length()] = true; // Case 2. s is empty for(int row = pattern.length() - 1;row >= 0;row--){ // if pattern contains only stars and s is empty only then it is true if(pattern[row] == '*' && dp[row + 1][s.length()] == true){ dp[row][s.length()] = true; }else{ dp[row][s.length()] = false; } } // filling the dp matrix(right to left and bottom to top) for(int row = pattern.length() -1;row >= 0;row--){ for(int col = s.length() - 1;col>=0;col--){ // if the characters of pattern and s is equal or patterns // rowth character is a ? then just pick up rigth bottom value if((pattern[row] == s[col]) || pattern[row] == '?'){ dp[row][col] = dp[row + 1][col + 1]; } // if there is a star then take the || of the bottom // adjacent, right adjacent and rigth-bottom value; else if(pattern[row] == '*'){ dp[row][col] = (dp[row+1][col] || dp[row+1][col+1] || dp[row][col+1]); } // otherwise store false else{ dp[row][col] = false; } } } return dp[0][0]; } // driver programme for the code int main() { string s, pattern; cin >> s; cin >> pattern; cout << s << endl; cout << pattern << endl; cout<<wildCard(pattern, s); return 0; }

**Output**

absbsbs a*?bs 1

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!