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”
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”
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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Minimum number of given operations required to make two strings equal
- Minimum number of operations required to make two strings equal
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
- Find the minimum number of preprocess moves required to make two strings equal
- Minimum number of swaps required to make the string K periodic
- Minimum edges required to add to make Euler Circuit
- Minimum characters required to make a password strong
- Minimum deletions required to make GCD of the array equal to 1
- Minimum removals required to make ranges non-overlapping
- Minimum changes required to make all element in an array equal
- Minimum operation required to make a balanced sequence
- Minimum swaps required to make a binary string divisible by 2^k
- Minimum swaps required to make a binary string alternating
- Minimum deletions required to make frequency of each letter unique
- Minimum increment/decrement operations required to make Median as X
- Minimum operations required to make every element greater than or equal to K
- Minimum array insertions required to make consecutive difference <= K
- Minimum operations required to make the string satisfy the given condition
- Minimum cost to make two strings same
- Minimum Cost To Make Two Strings Identical
Improved By : sanjeev2552