Minimum number of pairs required to make two strings same

Given two strings s1 and s2 of same length, the task is to count the minimum number of pairs of characters (c1, c2) such that by transforming c1 to c2 or c2 to c1 any number of times in any string make both the strings same.

Examples:

Input: s1 = “abb”, s2 = “dad”
Output: 2
Transform ‘a’ -> ‘d’, ‘b’ -> ‘a’ and ‘b’ -> ‘a’ -> ‘d’ in s1.
We can not take (a, d), (b, a), (b, d) as pairs because
(b, d) can be achieved by following transformation ‘b’ -> ‘a’ -> ‘d’

Input: s1 = “drpepper”, s2 = “cocacola”
Output: 7

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: This Problem can be solved by using Graphs or Disjoint Sets. Build an empty graph G and iterate through the strings. Add an edge in graph G only if one of the following conditions is met:

• Both s1[i] and s2[i] are not in G.
• s1[i] is in G but s2[i] is not in G.
• s2[i] is in G but s1[i] is not in G.
• There is no path from s1[i] to s2[i].

The minimum number of pairs will be the count of edges in the final graph G.

Below is the implementation of the above approach:

C++

 `// C++ implementation of the approach ` `#include ` `using` `namespace` `std; ` ` `  `// Function which will check if there is ` `// a path between a and b by using BFS ` `bool` `checkPath(``char` `a, ``char` `b,  ` `           ``map<``char``, vector<``char``>> &G) ` `{ ` `    ``map<``char``, ``bool``> visited; ` `    ``deque<``char``> queue; ` `    ``queue.push_back(a); ` `    ``visited[a] = ``true``; ` ` `  `    ``while` `(!queue.empty())  ` `    ``{ ` `        ``int` `n = queue.front(); ` `        ``queue.pop_front(); ` ` `  `        ``if` `(n == b) ``return` `true``; ` `        ``for` `(``auto` `i : G[n])  ` `        ``{ ` `            ``if` `(visited[i] == ``false``) ` `            ``{ ` `                ``queue.push_back(i); ` `                ``visited[i] = ``true``; ` `            ``} ` `        ``} ` `    ``} ` `    ``return` `false``; ` `} ` ` `  `// Function to return the  ` `// minimum number of pairs ` `int` `countPairs(string s1, string s2, ` `         ``map<``char``, vector<``char``>> &G, ``int` `x)  ` `{ ` `     `  `    ``// To store the count of pairs ` `    ``int` `count = 0; ` ` `  `    ``// Iterating through the strings ` `    ``for` `(``int` `i = 0; i < x; i++)  ` `    ``{ ` `        ``char` `a = s1[i]; ` `        ``char` `b = s2[i]; ` ` `  `        ``// Check if we can add an edge in the graph ` `        ``if` `(G.find(a) != G.end() and  ` `            ``G.find(b) == G.end() and a != b) ` `        ``{ ` `            ``G[a].push_back(b); ` `            ``G[b].push_back(a); ` `            ``count++; ` `        ``} ` `        ``else` `if` `(G.find(b) != G.end() and ` `                 ``G.find(a) == G.end() and a != b)  ` `        ``{ ` `            ``G[b].push_back(a); ` `            ``G[a].push_back(b); ` `            ``count++; ` `        ``}  ` `        ``else` `if` `(G.find(a) == G.end() and  ` `                 ``G.find(b) == G.end() and a != b)  ` `        ``{ ` `            ``G[a].push_back(b); ` `            ``G[b].push_back(a); ` `            ``count++; ` `        ``}  ` `        ``else` `        ``{ ` `            ``if` `(!checkPath(a, b, G) and a != b) ` `            ``{ ` `                ``G[a].push_back(b); ` `                ``G[b].push_back(a); ` `                ``count++; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``// Return the count of pairs ` `    ``return` `count; ` `} ` ` `  `// Driver Code ` `int` `main()  ` `{ ` `    ``string s1 = ``"abb"``, s2 = ``"dad"``; ` `    ``int` `x = s1.length(); ` `    ``map<``char``, vector<``char``>> G; ` `    ``cout << countPairs(s1, s2, G, x) << endl; ` ` `  `    ``return` `0; ` `} ` ` `  `// This code is contributed by ` `// sanjeev2552 `

Python3

 `# Python3 implementation of the approach ` `from` `collections ``import` `defaultdict, deque    ` `  `  `# Function which will check if there is  ` `# a path between a and b by using BFS ` `def` `Check_Path(a, b, G): ` `    ``visited ``=` `defaultdict(``bool``) ` `    ``queue ``=` `deque() ` `    ``queue.append(a) ` `    ``visited[a]``=` `True` `    ``while` `queue: ` `        ``n ``=` `queue.popleft() ` `        ``if` `n ``=``=` `b: ` `            ``return` `True` `        ``for` `i ``in` `list``(G[n]): ` `            ``if` `visited[i]``=``=` `False``: ` `                ``queue.append(i) ` `                ``visited[i]``=` `True` `    ``return` `False` `  `  `# Function to return the minimum number of pairs ` `def` `countPairs(s1, s2, G): ` `    ``name ``=` `defaultdict(``bool``) ` `     `  `    ``# To store the count of pairs ` `    ``count ``=` `0` `  `  `    ``# Iterating through the strings ` `    ``for` `i ``in` `range``(x): ` `        ``a ``=` `s1[i] ` `        ``b ``=` `s2[i] ` `  `  `        ``# Check if we can add an edge in the graph ` `        ``if` `a ``in` `G ``and` `b ``not` `in` `G ``and` `a !``=` `b: ` `            ``G[a].append(b) ` `            ``G[b].append(a) ` `            ``count``+``=` `1` `        ``elif` `b ``in` `G ``and` `a ``not` `in` `G ``and` `a !``=` `b: ` `            ``G[b].append(a) ` `            ``G[a].append(b) ` `            ``count``+``=` `1` `        ``elif` `a ``not` `in` `G ``and` `b ``not` `in` `G ``and` `a !``=` `b: ` `            ``G[a].append(b) ` `            ``G[b].append(a) ` `            ``count``+``=` `1` `        ``else``: ` `            ``if` `not` `Check_Path(a, b, G) ``and` `a !``=` `b: ` `                ``G[a].append(b) ` `                ``G[b].append(a) ` `                ``count``+``=` `1` `  `  `    ``# Return the count of pairs ` `    ``return` `count ` `  `  `# Driver code ` `if` `__name__``=``=``"__main__"``: ` `    ``s1 ``=``"abb"` `    ``s2 ``=``"dad"` `    ``x ``=` `len``(s1) ` `    ``G ``=` `defaultdict(``list``) ` `    ``print``(countPairs(s1, s2, G)) `

Output:

```2
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : sanjeev2552