The Wayback Machine - https://web.archive.org/web/20241128024355/https://www.geeksforgeeks.org/maximum-bipartite-matching/
Open In App

Maximum Bipartite Matching

Last Updated : 01 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 care? 
There are many real world problems that can be formed as Bipartite Matching. For example, consider the following problem:

“There are M job applicants and N jobs. Each applicant has a subset of jobs that he/she is interested in. Each job opening can only accept one applicant and a job applicant can be appointed for only one job. Find an assignment of jobs to applicants in such that as many applicants as possible get jobs.”

maximum_matching1

We strongly recommend to read the following post first. “Ford-Fulkerson Algorithm for Maximum Flow Problem”
Maximum Bipartite Matching and Max Flow Problem :

Maximum Bipartite Matching (MBP) problem can be solved by converting it into a flow network (See this video to know how did we arrive this conclusion). Following are the steps.
 

maximum_matching2

1) Build a Flow Network : There must be a source and sink in a flow network. So we add a source and add edges from source to all applicants. Similarly, add edges from all jobs to sink. The capacity of every edge is marked as 1 unit.

 

maximum_matching2

2) Find the maximum flow: We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the MBP we are looking for.

How to implement the above approach? 

Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘bpGraph[M][N]’ with M rows (for M job applicants) and N columns (for N jobs). The value bpGraph[i][j] is 1 if i’th applicant is interested in j’th job, otherwise 0. 

Output is number maximum number of people that can get jobs. 

A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space. 

Extra space can be reduced and code can be simplified using the fact that the graph is bipartite and capacity of every edge is either 0 or 1. The idea is to use DFS traversal to find a job for an applicant (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a job to the applicant.

In bpm(), we one by one try all jobs that an applicant ‘u’ is interested in until we find a job, or all jobs are tried without luck. For every job we try, we do following. 

If a job is not assigned to anybody, we simply assign it to the applicant and return true. If a job is assigned to somebody else say x, then we recursively check whether x can be assigned some other job. To make sure that x doesn’t get the same job again, we mark the job ‘v’ as seen before we make recursive call for x. If x can get other job, we change the applicant for job ‘v’ and return true. We use an array maxR[0..N-1] that stores the applicants assigned to different jobs.

If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM(). 

Recommended Practice

Implementation:

C++




// A C++ program to find maximal
// Bipartite matching.
#include <iostream>
#include <string.h>
using namespace std;
 
// M is number of applicants
// and N is number of jobs
#define M 6
#define N 6
 
// A DFS based recursive function
// that returns true if a matching
// for vertex u is possible
bool bpm(bool bpGraph[M][N], int u,
         bool seen[], int matchR[])
{
    // Try every job one by one
    for (int v = 0; v < N; v++)
    {
        // If applicant u is interested in
        // job v and v is not visited
        if (bpGraph[u][v] && !seen[v])
        {
            // Mark v as visited
            seen[v] = true;
 
            // If job 'v' is not assigned to an
            // applicant OR previously assigned
            // applicant for job v (which is matchR[v])
            // has an alternate job available.
            // Since v is marked as visited in
            // the above line, matchR[v] in the following
            // recursive call will not get job 'v' again
            if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
                                     seen, matchR))
            {
                matchR[v] = u;
                return true;
            }
        }
    }
    return false;
}
 
// Returns maximum number
// of matching from M to N
int maxBPM(bool bpGraph[M][N])
{
    // An array to keep track of the
    // applicants assigned to jobs.
    // The value of matchR[i] is the
    // applicant number assigned to job i,
    // the value -1 indicates nobody is
    // assigned.
    int matchR[N];
 
    // Initially all jobs are available
    memset(matchR, -1, sizeof(matchR));
 
    // Count of jobs assigned to applicants
    int result = 0;
    for (int u = 0; u < M; u++)
    {
        // Mark all jobs as not seen
        // for next applicant.
        bool seen[N];
        memset(seen, 0, sizeof(seen));
 
        // Find if the applicant 'u' can get a job
        if (bpm(bpGraph, u, seen, matchR))
            result++;
    }
    return result;
}
 
// Driver Code
int main()
{
    // Let us create a bpGraph
    // shown in the above example
    bool bpGraph[M][N] = {{0, 1, 1, 0, 0, 0},
                          {1, 0, 0, 1, 0, 0},
                          {0, 0, 1, 0, 0, 0},
                          {0, 0, 1, 1, 0, 0},
                          {0, 0, 0, 0, 0, 0},
                          {0, 0, 0, 0, 0, 1}};
 
    cout << "Maximum number of applicants that can get job is "
         << maxBPM(bpGraph);
 
    return 0;
}


Java




// A Java program to find maximal
// Bipartite matching.
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG
{
    // M is number of applicants
    // and N is number of jobs
    static final int M = 6;
    static final int N = 6;
 
    // A DFS based recursive function that
    // returns true if a matching for
    // vertex u is possible
    boolean bpm(boolean bpGraph[][], int u,
                boolean seen[], int matchR[])
    {
        // Try every job one by one
        for (int v = 0; v < N; v++)
        {
            // If applicant u is interested
            // in job v and v is not visited
            if (bpGraph[u][v] && !seen[v])
            {
                 
                // Mark v as visited
                seen[v] = true;
 
                // If job 'v' is not assigned to
                // an applicant OR previously
                // assigned applicant for job v (which
                // is matchR[v]) has an alternate job available.
                // Since v is marked as visited in the
                // above line, matchR[v] in the following
                // recursive call will not get job 'v' again
                if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
                                         seen, matchR))
                {
                    matchR[v] = u;
                    return true;
                }
            }
        }
        return false;
    }
 
    // Returns maximum number
    // of matching from M to N
    int maxBPM(boolean bpGraph[][])
    {
        // An array to keep track of the
        // applicants assigned to jobs.
        // The value of matchR[i] is the
        // applicant number assigned to job i,
        // the value -1 indicates nobody is assigned.
        int matchR[] = new int[N];
 
        // Initially all jobs are available
        for(int i = 0; i < N; ++i)
            matchR[i] = -1;
 
        // Count of jobs assigned to applicants
        int result = 0;
        for (int u = 0; u < M; u++)
        {
            // Mark all jobs as not seen
            // for next applicant.
            boolean seen[] =new boolean[N] ;
            for(int i = 0; i < N; ++i)
                seen[i] = false;
 
            // Find if the applicant 'u' can get a job
            if (bpm(bpGraph, u, seen, matchR))
                result++;
        }
        return result;
    }
 
    // Driver Code
    public static void main (String[] args)
                       throws java.lang.Exception
    {
        // Let us create a bpGraph shown
        // in the above example
        boolean bpGraph[][] = new boolean[][]{
                              {false, true, true,
                               false, false, false},
                              {true, false, false,
                               true, false, false},
                              {false, false, true,
                               false, false, false},
                              {false, false, true,
                               true, false, false},
                              {false, false, false,
                               false, false, false},
                              {false, false, false,
                               false, false, true}};
        GFG m = new GFG();
        System.out.println( "Maximum number of applicants that can"+
                            " get job is "+m.maxBPM(bpGraph));
    }
}


Python3




# Python program to find
# maximal Bipartite matching.
 
class GFG:
    def __init__(self,graph):
         
        # residual graph
        self.graph = graph
        self.ppl = len(graph)
        self.jobs = len(graph[0])
 
    # A DFS based recursive function
    # that returns true if a matching
    # for vertex u is possible
    def bpm(self, u, matchR, seen):
 
        # Try every job one by one
        for v in range(self.jobs):
 
            # If applicant u is interested
            # in job v and v is not seen
            if self.graph[u][v] and seen[v] == False:
                 
                # Mark v as visited
                seen[v] = True
 
                '''If job 'v' is not assigned to
                   an applicant OR previously assigned
                   applicant for job v (which is matchR[v])
                   has an alternate job available.
                   Since v is marked as visited in the
                   above line, matchR[v]  in the following
                   recursive call will not get job 'v' again'''
                if matchR[v] == -1 or self.bpm(matchR[v],
                                               matchR, seen):
                    matchR[v] = u
                    return True
        return False
 
    # Returns maximum number of matching
    def maxBPM(self):
        '''An array to keep track of the
           applicants assigned to jobs.
           The value of matchR[i] is the
           applicant number assigned to job i,
           the value -1 indicates nobody is assigned.'''
        matchR = [-1] * self.jobs
         
        # Count of jobs assigned to applicants
        result = 0
        for i in range(self.ppl):
             
            # Mark all jobs as not seen for next applicant.
            seen = [False] * self.jobs
             
            # Find if the applicant 'u' can get a job
            if self.bpm(i, matchR, seen):
                result += 1
        return result
 
 
bpGraph =[[0, 1, 1, 0, 0, 0],
          [1, 0, 0, 1, 0, 0],
          [0, 0, 1, 0, 0, 0],
          [0, 0, 1, 1, 0, 0],
          [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 1]]
 
g = GFG(bpGraph)
 
print ("Maximum number of applicants that can get job is %d " % g.maxBPM())
 
# This code is contributed by Neelam Yadav


C#




// A C# program to find maximal
// Bipartite matching.
using System;
 
class GFG
{
    // M is number of applicants
    // and N is number of jobs
    static int M = 6;
    static int N = 6;
 
    // A DFS based recursive function
    // that returns true if a matching
    // for vertex u is possible
    bool bpm(bool [,]bpGraph, int u,
             bool []seen, int []matchR)
    {
        // Try every job one by one
        for (int v = 0; v < N; v++)
        {
            // If applicant u is interested
            // in job v and v is not visited
            if (bpGraph[u, v] && !seen[v])
            {
                // Mark v as visited
                seen[v] = true;
 
                // If job 'v' is not assigned to
                // an applicant OR previously assigned
                // applicant for job v (which is matchR[v])
                // has an alternate job available.
                // Since v is marked as visited in the above
                // line, matchR[v] in the following recursive
                // call will not get job 'v' again
                if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
                                         seen, matchR))
                {
                    matchR[v] = u;
                    return true;
                }
            }
        }
        return false;
    }
 
    // Returns maximum number of
    // matching from M to N
    int maxBPM(bool [,]bpGraph)
    {
        // An array to keep track of the
        // applicants assigned to jobs.
        // The value of matchR[i] is the
        // applicant number assigned to job i,
        // the value -1 indicates nobody is assigned.
        int []matchR = new int[N];
 
        // Initially all jobs are available
        for(int i = 0; i < N; ++i)
            matchR[i] = -1;
 
        // Count of jobs assigned to applicants
        int result = 0;
        for (int u = 0; u < M; u++)
        {
            // Mark all jobs as not
            // seen for next applicant.
            bool []seen = new bool[N] ;
            for(int i = 0; i < N; ++i)
                seen[i] = false;
 
            // Find if the applicant
            // 'u' can get a job
            if (bpm(bpGraph, u, seen, matchR))
                result++;
        }
        return result;
    }
 
    // Driver Code
    public static void Main ()
    {
        // Let us create a bpGraph shown
        // in the above example
        bool [,]bpGraph = new bool[,]
                          {{false, true, true,
                            false, false, false},
                           {true, false, false,
                            true, false, false},
                           {false, false, true,
                            false, false, false},
                           {false, false, true,
                            true, false, false},
                           {false, false, false,
                            false, false, false},
                           {false, false, false,
                            false, false, true}};
        GFG m = new GFG();
    Console.Write( "Maximum number of applicants that can"+
                            " get job is "+m.maxBPM(bpGraph));
    }
}
 
//This code is contributed by nitin mittal.


PHP




<?php
// A PHP program to find maximal
// Bipartite matching.
 
// M is number of applicants
// and N is number of jobs
$M = 6;
$N = 6;
 
// A DFS based recursive function
// that returns true if a matching
// for vertex u is possible
function bpm($bpGraph, $u, &$seen, &$matchR)
{
    global $N;
     
    // Try every job one by one
    for ($v = 0; $v < $N; $v++)
    {
        // If applicant u is interested in
        // job v and v is not visited
        if ($bpGraph[$u][$v] && !$seen[$v])
        {
            // Mark v as visited
            $seen[$v] = true;
 
            // If job 'v' is not assigned to an
            // applicant OR previously assigned
            // applicant for job v (which is matchR[v])
            // has an alternate job available.
            // Since v is marked as visited in
            // the above line, matchR[v] in the following
            // recursive call will not get job 'v' again
            if ($matchR[$v] < 0 || bpm($bpGraph, $matchR[$v],
                                    $seen, $matchR))
            {
                $matchR[$v] = $u;
                return true;
            }
        }
    }
    return false;
}
 
// Returns maximum number
// of matching from M to N
function maxBPM($bpGraph)
{
    global $N,$M;
     
    // An array to keep track of the
    // applicants assigned to jobs.
    // The value of matchR[i] is the
    // applicant number assigned to job i,
    // the value -1 indicates nobody is
    // assigned.
    $matchR = array_fill(0, $N, -1);
 
    // Initially all jobs are available
 
    // Count of jobs assigned to applicants
    $result = 0;
    for ($u = 0; $u < $M; $u++)
    {
        // Mark all jobs as not seen
        // for next applicant.
        $seen=array_fill(0, $N, false);
 
        // Find if the applicant 'u' can get a job
        if (bpm($bpGraph, $u, $seen, $matchR))
            $result++;
    }
    return $result;
}
 
// Driver Code
 
// Let us create a bpGraph
// shown in the above example
$bpGraph = array(array(0, 1, 1, 0, 0, 0),
                    array(1, 0, 0, 1, 0, 0),
                    array(0, 0, 1, 0, 0, 0),
                    array(0, 0, 1, 1, 0, 0),
                    array(0, 0, 0, 0, 0, 0),
                    array(0, 0, 0, 0, 0, 1));
 
echo "Maximum number of applicants that can get job is ".maxBPM($bpGraph);
 
 
// This code is contributed by chadan_jnu
?>


Javascript




<script>
 
    // A JavaScript program to find maximal
    // Bipartite matching.
     
    // M is number of applicants
    // and N is number of jobs
    let M = 6;
    let N = 6;
   
    // A DFS based recursive function that
    // returns true if a matching for
    // vertex u is possible
    function bpm(bpGraph, u, seen, matchR)
    {
        // Try every job one by one
        for (let v = 0; v < N; v++)
        {
            // If applicant u is interested
            // in job v and v is not visited
            if (bpGraph[u][v] && !seen[v])
            {
                   
                // Mark v as visited
                seen[v] = true;
   
                // If job 'v' is not assigned to
                // an applicant OR previously
                // assigned applicant for job v (which
                // is matchR[v]) has an alternate job available.
                // Since v is marked as visited in the
                // above line, matchR[v] in the following
                // recursive call will not get job 'v' again
                if (matchR[v] < 0 || bpm(bpGraph, matchR[v],
                                         seen, matchR))
                {
                    matchR[v] = u;
                    return true;
                }
            }
        }
        return false;
    }
   
    // Returns maximum number
    // of matching from M to N
    function maxBPM(bpGraph)
    {
        // An array to keep track of the
        // applicants assigned to jobs.
        // The value of matchR[i] is the
        // applicant number assigned to job i,
        // the value -1 indicates nobody is assigned.
        let matchR = new Array(N);
   
        // Initially all jobs are available
        for(let i = 0; i < N; ++i)
            matchR[i] = -1;
   
        // Count of jobs assigned to applicants
        let result = 0;
        for (let u = 0; u < M; u++)
        {
            // Mark all jobs as not seen
            // for next applicant.
            let seen =new Array(N);
            for(let i = 0; i < N; ++i)
                seen[i] = false;
   
            // Find if the applicant 'u' can get a job
            if (bpm(bpGraph, u, seen, matchR))
                result++;
        }
        return result;
    }
     
    // Let us create a bpGraph shown
    // in the above example
    let bpGraph = [
      [false, true, true,
        false, false, false],
          [true, false, false,
            true, false, false],
              [false, false, true,
                false, false, false],
                  [false, false, true,
                    true, false, false],
                      [false, false, false,
                        false, false, false],
                          [false, false, false,
                            false, false, true]];
     
    document.write( "Maximum number of applicants that can"+
                       " get job is "+ maxBPM(bpGraph));
   
</script>


Output

Maximum number of applicants that can get job is 5

Time Complexity: O(V*E)

The time complexity of the above algorithm is O(V*E) where V is the number of vertices in the graph and E is the number of edges. The algorithm iterates over each vertex in the graph and then performs a DFS on the corresponding edges to find the maximum bipartite matching.

Space Complexity: O(V + E)

The space complexity of this algorithm is O(V + E) as it uses a two-dimensional boolean array to store the graph and an array to store the maximum matching.

You may like to see below also: 
Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) 
Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)



Previous Article
Next Article

Similar Reads

Maximum number of edges in Bipartite graph
Given an integer N which represents the number of Vertices. The Task is to find the maximum number of edges possible in a Bipartite graph of N vertices.Bipartite Graph: A Bipartite graph is one which is having 2 sets of vertices.The set are such that the vertices in the same set will never share an edge between them. Examples: Input: N = 10 Output:
3 min read
Maximum number of edges to be added to a tree so that it stays a Bipartite graph
A tree is always a Bipartite Graph as we can always break into two disjoint sets with alternate levels. In other words we always color it with two colors such that alternate levels have same color. The task is to compute the maximum no. of edges that can be added to the tree so that it remains Bipartite Graph. Examples: Input : Tree edges as vertex
6 min read
Minimum Bipartite Groups
Given Adjacency List representation of graph of N vertices from 1 to N, the task is to count the minimum bipartite groups of the given graph. Examples: Input: N = 5 Below is the given graph with number of nodes is 5: Output: 3 Explanation: Possible groups satisfying the Bipartite property: [2, 5], [1, 3], [4] Below is the number of bipartite groups
8 min read
Divide given Graph into Bipartite sets
Given a graph G(V, E), divide it into two sets such that no two vertices in a set are connected directly. If not possible print "Not Possible". Examples: Input: V = 7, E = 6, Edge = {{1, 2}, {2, 3}, {3, 4}, {3, 6}, {5, 6}, {6, 7}}Output: 7 5 1 3 6 2 4 Explanation: node {7, 5, 1, 3} are not connected directly and nodes {6, 2, 4} are not connected di
10 min read
Maximize number of edges added to convert given Tree into a Bipartite Graph
Given a tree of N nodes, the task is to find the maximum number of edges that can be added to the tree such that it becomes a bipartite graph. Note: Self loop or multiple edges are not allowed but cycles are permitted. Examples: Input: N = 4, Edges = {{1, 2}, {2, 3}, {1, 4}} 1 / \ 2 4 / 3Output: 1Explanation: An edge between nodes 3 and 4 can be ad
13 min read
Check Whether a Linked List is Bipartite or Not
Given a linked list representing a graph with directed edges, check whether the given linked list is a Bipartite graph or not. Examples: Input: 1->2->3->4->NULLOutput: PossibleExplanation: It is possible to color the above linked list using 2 colors. We can color node 1 and 3 with one color and node 2 and 4 with other color. Input: 1-
8 min read
Bipartite Graphs in Python
Bipartite graphs are a special type of graph where the nodes can be divided into two distinct sets, with no edges connecting nodes within the same set. Every edge connects a node from the first set to a node in the second set. What is a Bipartite Graph?A graph where the nodes can be divided into two sets, V1 and V2, such that no edges connect nodes
5 min read
Check if a given graph is Bipartite using DFS
Given an adjacency list representing a graph with V vertices indexed from 0, the task is to determine whether the graph is bipartite or not. Example: Input: Output: trueExplanation: The given graph can be colored in two colors so, it is a bipartite graph. Input: Output: falseExplanation: The given graph cannot be colored in two colors such that col
9 min read
Check whether a given graph is Bipartite or not
Given an adjacency list representing a graph with V vertices indexed from 0, the task is to determine whether the graph is bipartite or not. Example: Input: Output: trueExplanation: The given graph can be colored in two colors so, it is a bipartite graph. Input: Output: falseExplanation: The given graph cannot be colored in two colors such that col
9 min read
What is Bipartite Graph?
A bipartite graph can be colored with two colors such that no two adjacent vertices share the same color. This means we can divide the graph's vertices into two distinct sets where: All edges connect vertices from one set to vertices in the other set.No edges exist between vertices within the same set.An alternate definition: Formally, a graph G =
3 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
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
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
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
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 > 1. The operations that can be performed on String A are: Type 1: Select any index i (0 â‰Ī i< 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 >= 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
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. * --> Matches with 0 or more instances of any character or set of characters. ? --> Matches with any one charac
9 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
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
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
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
Matching the Alphanumerical Pattern in Matrix I
Given a 2D integer matrix mat[][] and a 2D character matrix pat[][]. Where 0 <= mat[r][c] <= 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
Article Tags :
Practice Tags :
three90RightbarBannerImg