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.


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

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:





# 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()
    visited[a]= True
    while queue:
        n = queue.popleft()
        if n == b:
            return True
        for i in list(G[n]):
            if visited[i]== False:
                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:
            count+= 1
        elif b in G and a not in G and a != b:
            count+= 1
        elif a not in G and b not in G and a != b:
            count+= 1
            if not Check_Path(a, b, G) and a != b:
                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))




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 or mail your article to 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.