The Wayback Machine - https://web.archive.org/web/20240917134030/https://www.geeksforgeeks.org/wildcard-pattern-matching/
Open In App

Wildcard Pattern Matching

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

wildcard-pattern-matching

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:  

  1. We can ignore ‘*’ character and move to next character in the Pattern.
  2. 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")

Output
Yes

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")

Output
Yes

Dry Run:

  • pattern = "a*b?d"
  • str = "aabxd"

Initial Setup:

  • pattern.length() = 5
  • str.length() = 5
  • dp[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] = '?'):
    • dp[1][4] = 0 (No match).
  • j = 5 (pattern[4] = 'd'):
    • dp[1][5] = 0 (No match).

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")

Output
Yes

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")

Output
Yes

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.



Previous Article
Next Article

Similar Reads

WildCard pattern matching having three symbols ( * , + , ? )
Given a text and a wildcard pattern, 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
14 min read
String matching where one string contains wildcard characters
Given two strings where first string may contain wild card characters and second string is a normal string. Write a function that returns true if the two strings match. The following are allowed wild card characters in first string. * --&gt; Matches with 0 or more instances of any character or set of characters. ? --&gt; Matches with any one charac
9 min read
Consonant and Vowel group check in String with Wildcard characters
Given a string S which is composed of lowercase alphabets and wildcard characters i.e. '?'. Here, '?' can be replaced by any of the lowercase alphabets, the task is to return 'True' if there are more than 3 consonants together or more than 5 vowels together else 'False'. Examples: Input: S = aeioup??Output: 0 Input: S = bcdaeiou??Output: 1 Approach
5 min read
Print all words matching a pattern in CamelCase Notation Dictionary
Given a dictionary of words where each word follows CamelCase notation, The task is to print all words in the dictionary that match with a given pattern consisting of uppercase characters only. Note: CamelCase is the practice of writing compound words or phrases such that each word or abbreviation begins with a capital letter. Common examples inclu
15+ min read
Matching the Alphanumerical Pattern in Matrix I
Given a 2D integer matrix mat[][] and a 2D character matrix pat[][]. Where 0 &lt;= mat[r][c] &lt;= 9 and each element of pat is either a digit or a lowercase English letter. The task is to find a submatrix of mat that matches pat. An integer matrix part matches pat if we can replace cells containing letters in pat with some digits (each distinct le
12 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction)
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matching for a given Bipartite Graph. We have di
3 min read
Longest Common Prefix Matching | Set-6
Given a set of strings, find the longest common prefix. Examples: Input: str[] = {geeksforgeeks, geeks, geek, geezer} Output: gee Input: str[] = {apple, ape, april} Output: ap Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach: Sort the given set of N strings.Compare the first and last string in the sorted array of strings.The string wi
6 min read
Applications of String Matching Algorithms
String matching algorithms have greatly influenced computer science and play an essential role in various real-world problems. It helps in performing time-efficient tasks in multiple domains. These algorithms are useful in the case of searching a string within another string. String matching is also used in the Database schema, Network systems.Let
5 min read
Count of matching set and unset bits in given integers.
For two integers X and Y are the tasks is to find the number of bits that are the same in their binary representation by not considering any leading zeroes after the leftmost set bit of the greater number in binary form. Examples: Input: X = 10, Y = 6Output: 2Explanation: The binary representation of 10 is 1010 and 6 is 0110. So, the number of same
8 min read
Difference summation with Array index matching
Given two sorted arrays A and B of size N and M respectively, the task is to find the value V, which is the summation of (A[j] - A[i]) for all pairs of i and j such that (j - i) is present in array B. Examples: Input: N = 4, M = 2, A[] = {1, 2, 3, 4}, B[] = {1, 3}Output: 6Explanation: Valid pairs of (i, j) are (1, 2), (2, 3), (3, 4), (1, 4). So the
7 min read
Maximize score by matching element with prediction and K switch are allowed
Given an array arr[] of size N, with values either 1, 2, or 3. Traverse the array from left to right and before traversal predict one number from 1, 2, or 3, if arr[i] is matched with the prediction score will be increased by 1. The prediction can be switched at most K times. Find the maximum score possible. Examples: Input: A[] = {1, 1, 2, 1, 3},
12 min read
Count the Number of matching characters in a pair of strings
Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: Input: str1 = "abcdef", str2 = "defghia" Output: 4 Matching characters are: a, d, e, fInput: str1 = "aabcddekll12", str2 = "bb22ll@55k" O
7 min read
Maximum Bipartite Matching
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matchings for a given Bipartite Graph. Why do we
15+ min read
Word matching by swapping and incrementing characters
Given two strings A and B, determine if string A can be made equal to string B by performing some operations on string A any number of times. Before starting the operations, we have to choose an integer K &gt; 1. The operations that can be performed on String A are: Type 1: Select any index i (0 â‰Ī i&lt; length(A)-1) and swap(A[i], A[i+1]).Type 2: S
10 min read
String matching with * (that matches with any) in any of the two strings
You are given two strings A and B. Strings also contains special character * . you can replace * with any alphabetic character. Finally, you have to tell whether it is possible to make both string same or not. Examples: Input : A = "gee*sforgeeks" B = "geeksforgeeks"Output :YesInput :A = "abs*" B = "abds"Output :NoExplanation: How we can solve abov
10 min read
Longest Prefix Subsequence matching Fibonacci Sequence
Given an array arr of size N. Also, there is another array B of the infinite size where B[0] = B[1] = 1, and for all (i &gt;= 2), B[i] = B[i-1]+B[i-2], the task is to find the length of the longest subsequence which is the prefix of array B. If there is no subsequence which is the prefix of array B then return 0. Examples: Input: N = 6, arr = {1, 2
5 min read
Longest prefix matching - A Trie based solution in Java
Given a dictionary of words and an input string, find the longest prefix of the string which is also a word in dictionary. Examples: Let the dictionary contains the following words: {are, area, base, cat, cater, children, basement} Below are some input/output examples: -------------------------------------- Input String Output ---------------------
4 min read
Longest Common Prefix using Word by Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended PracticeLongest Common Prefix in an ArrayTry It! We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest co
15 min read
Longest Common Prefix using Character by Character Matching
Given a set of strings, find the longest common prefix. Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed word by word matching algorithm in previous post.In this algorithm, instead
13 min read
Find first non matching leaves in two binary trees
Given two binary trees, find the first leaves of two trees that do not match. If there are no non-matching leaves, print nothing. Examples: Input : First Tree 5 / \ 2 7 / \ 10 11 Second Tree 6 / \ 10 15 Output : 11 15 If we consider leaves of two trees in order, we can see that 11 and 15 are the first leaves that do not match. Method 1 (Simple) : D
14 min read
Prefix matching in Python using pytrie module
Given a list of strings and a prefix value sub-string, find all strings from given list of strings which contains given value as prefix ? Examples: Input : arr = ['geeksforgeeks', 'forgeeks', 'geeks', 'eeksfor'], prefix = 'geek' Output : ['geeksforgeeks','geeks'] A Simple approach to solve this problem is to traverse through complete list and match
2 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)
We strongly recommend to refer below post as a prerequisite.Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) There are few important things to note before we start implementation. We need to find an augmenting path (A path that alternates between matching and not matching edges and has free vertices as starting and ending points)
13 min read
CSES Solutions - String Matching
Given a string S and a pattern P, your task is to count the number of positions where the pattern occurs in the string. Examples: Input: S = "saippuakauppias", P = "pp"Output: 2Explanation: "pp" appears 2 times in S. Input: S = "aaaa", P = "aa"Output: 3Explanation: "aa" appears 3 times in S. Approach: To solve the problem, follow the below idea: To
7 min read
CSES Solutions - Tree Matching
You are given a tree consisting of n nodes. A matching is a set of edges where each node is an endpoint of at most one edge. What is the maximum number of edges in a matching ? Examples: Input : N = 10 , edges = {{5,8}, {4,6}, {9,1}, {10,4}, {1,3}, {2,3}, {7,9}, {6,2}, {5,10}}Output : 5 Explanation : One possible matching is {5-8 , 10-4, 1-3, 7-9 ,
9 min read
Implementing Regular Expression Matching
Given two strings S and P where S consists of only lowercase English alphabets while P consists of lowercase English alphabets as well as special characters '.' and '*', the task is to implement a function to test regular expression such that: '.' Matches any single character.​​​​'*' Matches zero or more of the preceding element.Note: For each appe
9 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Decode a given pattern in two ways (Flipkart Interview Question)
A sender sends a binary string to a receiver meanwhile he encrypt the digits. You are given a encrypted form of string. Now, the receiver needs to decode the string, and while decoding there were 2 approaches. Let the encrypted binary string be P[] and actual string be S[]. First, receiver starts with first character as 0; S[0] = 0 // First decoded
8 min read
Print a String in wave pattern
Given a string, you need to transform this string in the form of a wave pattern Examples: Input : GeeksforGeeks, 2 Output : G e s o G e s e k f r e k Input : GeeksforGeeks, 4 Output : G o s e f r k e s G e k e C/C++ Code // CPP program to print wave pattern // of a given string // This is a modified code of // https://www.geeksforgeeks.org/print-co
7 min read
Find the element at R'th row and C'th column in given a 2D pattern
Given two integers R and C, the task is to find the element at the Rth row and Cth column.Pattern: First Element of ith row =[Tex]\frac{i*(i-1)}{2} + 1[/Tex]Every element is a Arithmetic progression increasing difference where common difference is 1.Initial Difference Term = [Tex]i + 1[/Tex] Examples: Input: R = 4, C = 4 Output: 25 Explanation: Pat
5 min read
Program for diamond pattern with different layers
Given a number n and using 0-n numbers you have to print such a pattern.Examples: Input : n = 5 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 4 5 4 3 2 1 0 0 1 2 3 4 3 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 Input : n = 3 Output : 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 The idea here is to count the space in beginning o
10 min read