Open In App

Minimum number of pairs required to make two strings same

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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

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 <bits/stdc++.h>
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


Java




import java.util.*;
 
public class Main
{
 
  // Function which will check if there is
  // a path between a and b by using BFS
  public static boolean checkPath(char a, char b, Map<Character, List<Character>> G) {
    Map<Character, Boolean> visited = new HashMap<>();
    Deque<Character> queue = new LinkedList<>();
    queue.addLast(a);
    visited.put(a, true);
    while (!queue.isEmpty()) {
      char n = queue.removeFirst();
      if (n == b) return true;
      List<Character> edges = G.get(n);
      for (char i : edges) {
        if (!visited.containsKey(i)) {
          queue.addLast(i);
          visited.put(i, true);
        }
      }
    }
    return false;
  }
 
  // Function to return the
  // minimum number of pairs
  public static int countPairs(String s1, String s2, Map<Character, List<Character>> G, int x) {
    int count = 0;
    for (int i = 0; i < x; i++) {
      char a = s1.charAt(i);
      char b = s2.charAt(i);
      if (G.containsKey(a) && !G.containsKey(b) && a != b) {
        G.put(a, new ArrayList<>(Arrays.asList(b)));
        G.put(b, new ArrayList<>(Arrays.asList(a)));
        count++;
      } else if (G.containsKey(b) && !G.containsKey(a) && a != b) {
        G.put(b, new ArrayList<>(Arrays.asList(a)));
        G.put(a, new ArrayList<>(Arrays.asList(b)));
        count++;
      } else if (!G.containsKey(a) && !G.containsKey(b) && a != b) {
        G.put(a, new ArrayList<>(Arrays.asList(b)));
        G.put(b, new ArrayList<>(Arrays.asList(a)));
        count++;
      } else {
        if (!checkPath(a, b, G) && a != b) {
          List<Character> aEdges = G.get(a);
          aEdges.add(b);
          G.put(a, aEdges);
          List<Character> bEdges = G.get(b);
          bEdges.add(a);
          G.put(b, bEdges);
          count++;
        }
      }
    }
    return count-1;
  }
 
  // Driver code
  public static void main(String[] args) {
    String s1 = "abb";
    String s2 = "dad";
    int x = s1.length();
    Map<Character, List<Character>> G = new HashMap<>();
    System.out.println(countPairs(s1, s2, G, x));
  }
}
 
// This code is contributed by lokeshpotta20.


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


C#




using System;
using System.Collections.Generic;
 
namespace Main
{
class Program
{
// Function which will check if there is
// a path between a and b by using BFS
public static bool CheckPath(char a, char b, Dictionary<char, List<char>> G)
{
Dictionary<char, bool> visited = new Dictionary<char, bool>();
Queue<char> queue = new Queue<char>();
queue.Enqueue(a);
visited[a] = true;
 
 
        while (queue.Count > 0)
        {
            char n = queue.Dequeue();
            if (n == b)
                return true;
            List<char> edges = G[n];
            foreach (char i in edges)
            {
                if (!visited.ContainsKey(i))
                {
                    queue.Enqueue(i);
                    visited[i] = true;
                }
            }
        }
        return false;
    }
 
    // Function to return the
    // minimum number of pairs
    public static int CountPairs(string s1, string s2, Dictionary<char, List<char>> G, int x)
    {
        int count = 0;
        for (int i = 0; i < x; i++)
        {
            char a = s1[i];
            char b = s2[i];
            if (G.ContainsKey(a) && !G.ContainsKey(b) && a != b)
            {
                G[a] = new List<char>(new char[] { b });
                G[b] = new List<char>(new char[] { a });
                count++;
            }
            else if (G.ContainsKey(b) && !G.ContainsKey(a) && a != b)
            {
                G[b] = new List<char>(new char[] { a });
                G[a] = new List<char>(new char[] { b });
                count++;
            }
            else if (!G.ContainsKey(a) && !G.ContainsKey(b) && a != b)
            {
                G[a] = new List<char>(new char[] { b });
                G[b] = new List<char>(new char[] { a });
                count++;
            }
            else
            {
                if (!CheckPath(a, b, G) && a != b)
                {
                    List<char> aEdges = G[a];
                    aEdges.Add(b);
                    G[a] = aEdges;
                    List<char> bEdges = G[b];
                    bEdges.Add(a);
                    G[b] = bEdges;
                    count++;
                }
            }
        }
        return count - 1;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        string s1 = "abb";
        string s2 = "dad";
        int x = s1.Length;
        Dictionary<char, List<char>> G = new Dictionary<char, List<char>>();
        Console.WriteLine(CountPairs(s1, s2, G, x));
    }
}
}


Javascript




// JavaScript implementation of the approach
 
// Function which will check if there is
// a path between a and b by using BFS
function Check_Path(a, b, G) {
  const visited = {};
  const queue = [];
  queue.push(a);
  visited[a] = true;
  while (queue.length) {
    const n = queue.shift();
    if (n === b) {
      return true;
    }
    for (let i = 0; i < G[n].length; i++) {
      if (!visited[G[n][i]]) {
        queue.push(G[n][i]);
        visited[G[n][i]] = true;
      }
    }
  }
  return false;
}
 
// Function to return the minimum number of pairs
function countPairs(s1, s2, G) {
  const name = {};
   
  // To store the count of pairs
  let count = 0;
 
  // Iterating through the strings
  for (let i = 0; i < x; i++) {
    const a = s1[i];
    const b = s2[i];
 
    // Check if we can add an edge in the graph
    if (G[a] && !G[b] && a !== b) {
      G[a].push(b);
      G[b] = [a];
      count++;
    } else if (G[b] && !G[a] && a !== b) {
      G[b].push(a);
      G[a] = [b];
      count++;
    } else if (!G[a] && !G[b] && a !== b) {
      G[a] = [b];
      G[b] = [a];
      count++;
    } else {
      if (!Check_Path(a, b, G) && a !== b) {
        G[a].push(b);
        G[b] = [a];
        count++;
      }
    }
  }
 
  // Return the count of pairs
  return count;
}
 
// Driver code
const s1 = "abb";
const s2 = "dad";
const x = s1.length;
const G = {};
console.log(countPairs(s1, s2, G));
 
// This code is contributed by rishabmalhdijo


Output:

2

Time Complexity: O(x) where x is the length of the first string.

Space Complexity: O(x) where x is the length of the string



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads